samedi 29 septembre 2018

Images are not loading after Transferred Laravel Website on server

I have transferred website from local to web server, mean while i changed some scenarios.

1- I have changed folder structure and moved public folder files on root.

2- Image files are being uploaded into store folder while symbolic storage folder is moved on root also.

But after moving public folder files on root images not working. while uploaded images are being stored into main storage folder. but not linked with symbolic storage folder. so help me how can i attach again both storage folders.

Storage folder related code into config/filesystem is shown below:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/pulic/images/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_KEY'),
        'secret' => env('AWS_SECRET'),
        'region' => env('AWS_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

],

main storage folder path is:

Root/Laravel_files/storage/app/public/images

while symbolic storage folder address is:

Root/storage/images



via Chebli Mohamed

jeudi 27 septembre 2018

Laravel: Why does eager loading only keep results for last model?

If I execute the following:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9])
                    ->get();

Then I get the following result:

Illuminate\Database\Eloquent\Collection {#1104
 all: [
   App\Assignment {#1112
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#986
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#945
         all: [
           App\Record {#853
             id: 6624,
             unit_id: 6,
             process_date: "2017-09-19",
             process_hour: 14,
           },
         ],
       },
     },
   },
 ],
}

Note how the loaded unit has a record that matches the query.

Now, if I use the exact same query but add another assignment (49) to my whereIn array:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9,49])
                    ->get();

The record for assignment 49 is shown, but the record for assignment 9 does not show up anymore:

Illuminate\Database\Eloquent\Collection {#1032
 all: [
   App\Assignment {#1014
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#1283
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#1254
         all: [],
       },
     },
   },
   App\Assignment {#1061
     id: 49,
     unit_id: 29,
     start_date: "2017-02-24",
     end_date: "9999-12-31",
     unit: App\Unit {#1279
       id: 29,
       records: Illuminate\Database\Eloquent\Collection {#1131
         all: [
           App\Record {#1284
             id: 6062,
             unit_id: 29,
             process_date: "2017-03-10",
             process_hour: 13,
           },
         ],
       },
     },
   },
 ],
}

The record that matches the criteria for assignment 9 obviously exists, but for some reason it doesn't get loaded when the query finds more than one assignment with a unit/record that matches the criteria.

I tested this with more assignments as well, and in each case the record will only show up for the last assignment in the array.

What's the deal here?



via Chebli Mohamed

mercredi 26 septembre 2018

Laravel-echo socket polling failed

I trying to implement socket connection in my laravel5.1 web application My web app running in docker containers.

I have setup laravel-echo-server using [kylestev/laravel-echo-server][1], and its running as expected

enter image description here

import Echo from "laravel-echo"
window.io = require('socket.io-client');

if (typeof io !== 'undefined') {
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001',
    });
}

window.Echo.channel('test-event')
    .listen('Eventname', (e) => {
        console.log(e);
});

when i load the page in browser the polling request failing with EMPTY_RESPONSE error.

enter image description here

    {
    "authHost": null,
    "authEndpoint": null,
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "redis"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "hms.zuzurooms.local",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}



via Chebli Mohamed

dimanche 23 septembre 2018

why i am getting No query results for model in laravel?

When i search by city name which is available in my database table it will show the result but when i search by unknown city which is not available in my database table it says -No query results for model [App\City]. i am sharing you the code and screenshot see error screenshot actually i want to redirect to 401 page if the city is not found in my database table

Here is my route

Route::get('teacher-jobs-by-city/{city}','TeacherJobsController@by_location');

Here is my function

public function by_location($location_id='') {

$data= array();
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
$items= Subject::orderBy('id','asc')->get();
$data['location']=$location;

      //$subjects = [''=>'Select Subject'] + Subject::lists('subject_title','id')->toArray();
      //$city = [''=>'Select City'] + City::lists('name','id')->toArray();
        $active_class ='Select Subject to see job Openings';
        return view('frontend.teacherjobs.by_location',compact('active_class','data','items'));

    }



via Chebli Mohamed

samedi 22 septembre 2018

Laravel: Sorting Polymophic Relations

REQUIREMENTS

  1. In the Student Controller, the results must be sorted by student name.

  2. The results must be sorted by student's guardian name.



TABLE STRUCTURE

  • taxonomies

    • id
    • entity_type - It contains the class name of the owning model.
    • entity_id - It contains the ID value of the student.
  • students

    • id
    • name
  • guardians

    • id
    • student_id
    • name



CONTROLLER

  • StudentController.php

    public function getStudents()
    {
        return Taxonomy::with([
                'entity', 
                'entity.guardian'
            ])
            ->where('entity_type', 'Student')
            ->get();
    }
    
    



MODEL

  • Taxonomy.php

    public function entity()
    {
        return $this->morphTo();
    }
    
    
  • Student.php

    public function taxonomies()
    {
        return $this->morphMany('App\Taxonomy', 'entity');
    }
    
    public function guardian()
    {
        return $this->hasOne('App\Guardian');
    }
    
    
  • Guardian.php

    public function student()
    {
        return $this->belongsTo('App\Student');
    }
    
    


via Chebli Mohamed

jeudi 20 septembre 2018

Auth.password class is not found

Laravel version: 5.1

This is a project which started in L4.2. I upgraded it to L5.1 and I am trying to fix issues. The app has its own password reset functionality which utilizes laravel reset() function.

I am trying to call Password::reset() but I am getting the error of password reset class is not found. I have the Illuminate\Auth\Passwords\PasswordResetServiceProvider::class and alias password registered in config app file but I am still getting the error auth.password class not found.



via Chebli Mohamed

dimanche 16 septembre 2018

Access user via Authorizer in model definition

In Laravel 5.1 with OAuth2, I want to eager load a model, but place query params (from user model) on the eager loaded model. The easiest way I thought to do this was directly on the model.

More specifically, Activity belongsTo Task. I only want to load activities for the task where they match certain criteria on the user object. Using OAuth2, I attempt to find the user via Authorizer, then access its properties. The route is wrapped in Lucadegasperi's middleware

$router->group(['middleware' => 'oauth'], function(Router $router) {
       $router->get('tasks/{task}', 'Resources\Tasks@show');

And the request header seems to pass along the bearer token just fine.

I'm able to access the user via Authorizer within the controller, but not in the model definition. Why is this?

I'm getting error:

NoActiveAccessTokenException in Authorizer.php line 104: Tried to access session data without an active access token

use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use App\User;

class Task extends BaseModel
{
    protected $with = ['activities'];

    public function activities()
    {
        $user = User::find(Authorizer::getResourceOwnerId());
        return $this->hasMany(Activity::class)->where('id', '=', $user->...);
    }



via Chebli Mohamed

samedi 15 septembre 2018

how to make db in laravel using mysql for multiple users, like in my case Admin, Users, Agents, International Agents

i want to design a db for my project in laravel but confused how to manage tables. I have four entities Admin, Users, Agents and International Agents. Please help me how i manage my db tables. and if i make single table for multiple users then how to identify users. Note: Each of the mentioned entities are different. Please ask if it not sounds clear. Thanks



via Chebli Mohamed

Laravel Problem credentials do not match our records

First of all Sorry for my bad english.

I am new to laravel. I have recently run into some problems with authentication/login system which comes built-in in laravel by the command make:auth.

The registration process is working correctly and after that it logs me in automatically. but when I log out and try to log back in, I get this error:

These credentials do not match our records.

I'm not sure whats wrong! but i tried to search error on google stack overflow and etc. The solution i found is this. These credentials do not match our records, laravel 5.2 but it also didn't work.

This is my code.

Http/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;


class LoginController extends Controller
{

    use AuthenticatesUsers;


    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }


}

This is model

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'user_name', 'email','user_password','user_created_by',
    ];

    protected $hidden = [
        'user_password', 'remember_token',
    ];

    protected $primaryKey = 'user_id';

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

This is View

Views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="">
                        

                        <div class="form-group">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" > Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

This is User Table

User Table



via Chebli Mohamed

vendredi 14 septembre 2018

Hide row when result of spesific column is null in Datatable Jquery automatically?

i want to ask about how to hide one row, in example one row contain 10 columns, the first and second column is filled with right value, but third until end value is null, i want to hide the row that have the condition like that. i've tried to make filter before its rendered but not work, please help. This is my code

oTable = $('#data').DataTable({
   "ordering":true,
   "columns": [
   {data: 'no', name: 'no'},
   {data: 'number', name: 'number'},
   {data: 'action', name: 'action'},
   {data: 'status', name: 'status'},],});
   //Used For Call Data (AJAX)

<table id="data" class="table table-striped table-bordered display" style="width: 100%; overflow-x: scroll" >
  <thead>
  <tr>
    <th style="width: 25px">No</th>
    <th>No</th>
    <th>Action<br></th>
    <th>Current Status</th>
  </tr>
 //Used to make table

Thank you. Any idea and help will much appreciated



via Chebli Mohamed

jeudi 13 septembre 2018

How to sotre an id from a collection on to another collection of MongoDB in Laravel

I have two Collection category and subcategory. One category can have 0 or more subcategories that's why i need relation between them how can i store _id oa document form category collection to subcategory collection's document.

category

{
    "_id" : ObjectId("5b8abe366a44fa2d080065d2"),
    "Title" : "Aptitude",
    "Description" : "Aptitude",
    "Slug" : "aptitude",
    "updated_at" : ISODate("2018-09-01T16:28:38Z"),
    "created_at" : ISODate("2018-09-01T16:28:38Z")
 }

subcategory

{
    "_id" : ObjectId("5b9abbd06a44fa207c001674"),
    "Title" : "Aithmatic Apptitude",
    "Description" : "Aithmatic Apptitude",
    "Slug" : "arithmatic_aptitude",
    "CategoryId" : "5b8abe366a44fa2d080065d2",
    "updated_at" : ISODate("2018-09-13T19:34:40Z"),
    "created_at" : ISODate("2018-09-13T19:34:40Z")
}
{
    "_id" : ObjectId("5b9ac7e86a44fa207c001678"),
    "Title" : "Reasoning",
    "Description" : "Reasoning",
    "Slug" : "reasoning",
    "CategoryId" : "5b8abe366a44fa2d080065d2",
    "updated_at" : ISODate("2018-09-13T20:26:16Z"),
    "created_at" : ISODate("2018-09-13T20:26:16Z")
}

As you can see i am storing the category_id on subcategory collection a string "CategoryId" : "5b8abe366a44fa2d080065d2",

Here is my code for storing

$subcategory = Subcategory::create(
    [
        'Title' => $request->Title, 
        'Description' => $request->Description,
        'Slug' => $request->Slug,
        'CategoryId' =>  $request->CategoryId,
    ]

);

Want to sore it like actual reference"category_id" ObjectId("5b8abe366a44fa2d080065d2") . convert this command db.subcategory.insert({Title:"Example",Description:"Example", Slug:"Example",CategoryId:db.category.find({_id:"5b9abc8cb3562ec4e990ec5b"})._id}) how can it be possible, Please help



via Chebli Mohamed

Whan to Show some data On my view but there is a Error In Laravel

Here I am trying to add, Add Comment feature and it's causing a problem to show data.

public function store(Request $request)
{
    $chatterreply =  new Chatterreply;
    $chatterreply->reply = $request->body;
    $chatterreply->chatter_post_id = $request->chatter_post_id;
    $chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
    $chatterreply->save();
    $chatterreplies = Chatterreply::where('chatter_post_id',$request->chatter_post_id)->get();
     $chatter_editor = config('chatter.editor');

    if ($chatter_editor == 'simplemde') {
        // Dynamically register markdown service provider
        \App::register('GrahamCampbell\Markdown\MarkdownServiceProvider');
    }
    echo "<pre>"; print_r($chatterreplies); die;
    return view('chatter::discussion', compact('chatterreplies','chatter_editor'))->with('chatter_alert','Add Comment Successfully');

}

And Here Is Where I am passing the variable

 $chatter = session()->pull('chatter');
            return view('chatter::discussion', compact('discussion', 'posts', 'chatter_editor'))->with('chatterreplies',$chatter);



via Chebli Mohamed

How to prevent the main Laravel form to submit?

I have 1 main form. I also have a sub form inside that main form.

I can't seem to prevent the main form to stop submitting since the button type submit will submit the main form automatically.

That is my entire form

enter image description here

My subform is my delete of each image

enter image description here

edit.blade.php

@extends('layouts.be.master')
@section('content')

<script type="text/javascript" src="/js/ckeditor.js"></script>
<link rel="stylesheet" type="text/css" href="http://d.biossusa.com/css/root/hover-master/hover.css">

<style type="text/css">
.portfolio-images {
    border: solid 1px silver;
}

._hover{
    padding: 0px;
    position: relative;
    overflow: hidden;
    border: 1px solid #D8D8D8;
    /*border-radius: 10px;*/
}
._hover:hover .caption{
    opacity: 1;
    transform: translateY(-150px);
    -webkit-transform:translateY(-150px);
    -moz-transform:translateY(-150px);
    -ms-transform:translateY(-150px);
    -o-transform:translateY(-150px);
}
._hover img{
    z-index: 4;
}
._hover .caption{
    position: absolute;
    top:150px;
    -webkit-transition:all 0.3s ease-in-out;
    -moz-transition:all 0.3s ease-in-out;
    -o-transition:all 0.3s ease-in-out;
    -ms-transition:all 0.3s ease-in-out;
    transition:all 0.3s ease-in-out;
    width: 100%;
}
._hover .blur{
    background-color: rgba(0,0,0,0.8);
    height: 300px;
    z-index: 5;
    position: absolute;
    width: 100%;
}
._hover .caption-text{
    z-index: 10;
    color: #fff;
    position: absolute;
    height: 300px;
    text-align: center;
    top:-20px;
    width: 100%;

}
</style>


<?php $tags = explode(",", $portfolio->tag ); ?>

<div class="card-body card-padding">
    <div class="row">

        {!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'portfolio/'. $portfolio->id .'/update','files' => true)) !!}


        <div class="col-sm-12">

            
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-10">
                    <input type="text" value="" name="name" class="form-control" id="name" placeholder="Name">
                </div>
            </div>

            
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">Type</label>
                <div class="col-sm-10">
                    <select name="type" class="form-control">
                      @foreach($portfolioTypes as $item)
                      <option value=""></option>
                      @endforeach
                  </select>
              </div>
          </div>


          
          <div class="form-group">
            <label for="email" class="col-sm-2 control-label">Tags</label>
            <div class="col-sm-10">

            </div>

            <input id="tags" name="tag">
        </div>

        
        <div class="form-group">
            <label for="url" class="col-sm-2 control-label">URL</label>
            <div class="col-sm-10">
                <input name="url" type="text" value="" class="form-control" placeholder="URL">
            </div>
        </div>


        


        <div class="form-group">

            <label for="email" class="col-sm-2 control-label">Images</label>


            @foreach($images as $image)

                <?php

                $crop_img = str_replace('full.jpg','crop.jpg',$image->img_path);

                ?>


                <div class="col-sm-2">

                    <div class="_hover " style="background: transparent;">
                        <p style="text-align:center;">
                            <img class="img-responsive" src="" alt="">
                        </p>
                        <div class="caption">
                            <div class="blur"></div>
                            <div class="caption-text">
                                <h6 class="title lighter" style="padding:5px;border-radius: 10px;">
                                    
                                </h6>
                                <p>
                                    <span>
                                        <a data-toggle="modal"  data-target="#delete_image_">
                                            delete
                                        </a>
                                    </span>

                                </p>

                            </div>
                        </div>
                    </div>
                </div>


                <div class="modal fade" id="delete_image_">
                    <div class="model-content" style="margin-top: 200px;">
                        <div class="col-sm-offset-4 col-sm-4 ">

                        {!! Form::model($image, array( 'url' => '/portfolio/image/'.$image->id.'/destroy','method' => 'DELETE')) !!}

                            <button type="submit" class="btn btn-danger btn-lg btn-block">Delete ()</button>
                          <a class="btn btn-primary btn-lg btn-block" data-dismiss="modal" > Cancel </a>

                        {!! Form::hidden('$id', $image->id)!!}
                        {!! Form::close()!!}
                        </div>
                    </div>
                </div>



            @endforeach

            <br><br>

            <input id="images" name="images[]" type="file"  multiple>

        </div>

        
        <div class="form-group">

            <label for="email" class="col-sm-2 control-label">Description</label>
            <div class="col-sm-10">

                <textarea name="description" rows="20" cols="80" id="description">
                    
                </textarea>
                <script>
                    CKEDITOR.replace( 'description' );
                </script>

            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-8">
                <a class="btn btn-default" href="/portfolio"> Cancel </a>
                <button type="submit" class="btn btn-info">Done</button>
            </div>
        </div>

        </div>

        {!!Form::close()!!}


    </div>
</div>


@stop

@section('custom-scripts')

<link rel="stylesheet" type="text/css" href="/css/jquery.tag-editor.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

<script type="text/javascript" src="/js/jquery.caret.min.js"></script>
<script type="text/javascript" src="/js/jquery.tag-editor.js"></script>

<script type="text/javascript">
    $( "select[name*='type']" ).val("");

    function readLogo(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#portfolio-icon').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $( "input[name*='logo_path']" ).change(function(){
        readLogo(this);
    });


    $('#tags').tagEditor({

        autocomplete: {
            delay: 0,
            position: { collision: 'flip' },
            source: [<?php echo '"'.implode('","', $skillList).'"' ?>]
        },
        forceLowercase: false,
        delimiter: ',', /* space and comma */
        placeholder: 'Enter tags ...',
        initialTags: [<?php echo '"'.implode('","', $tags).'"' ?>]

    });

</script>
@stop



Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

Upload Multiple Images in Laravel 5.1

I have an input file

<input id="images" name="images" type="file"  multiple>

I upload 3 files

enter image description here

My controller only receive 1.

$files = Request::file('images');
$file_count = count($files);

dd($file_count); // 1


dd($files);

UploadedFile {#28 ▼
  -test: false
  -originalName: " 2018-09-13 at 11.54.24 AM.png"
  -mimeType: "image/png"
  -size: 5849
  -error: 0
}

What did I miss ?



via Chebli Mohamed

Undefined variable: request - Laravel 5.1

I have include this on top of my file

use Request;

and also,

use Illuminate\Http\Request;


When I tried use

$files = $request->file('images');
dd($files);

I kept getting

ErrorException in PortfolioController.php line 113: Undefined variable: request

Why ?

According to the doc of 5.1

https://laravel.com/docs/5.1/requests

use Illuminate\Http\Request;

should be enough.


Controller

public function update($id) {

    $files = $request->file('images');

    ...

}



via Chebli Mohamed

mardi 11 septembre 2018

MethodNotAllowedHttpException in RouteCollection.php line 200:

I have these route declaration here

//Skill
Route::get('skill','SkillController@index');
Route::get('skill/create','SkillController@create');
Route::post('skill/store','SkillController@store');
Route::get('skill/{id}','SkillController@show');
Route::get('skill/{id}/edit', 'SkillController@edit');
Route::post('skill/{id}/update','SkillController@update');
Route::delete('skill/{id}/destroy','SkillController@destroy');

With these routes, I can delete fine on local.

When I tried to delete on production, I kept getting

enter image description here

I know for sure, I had this line

Route::delete('skill/{id}/destroy','SkillController@destroy');

  • Local and Prod have the same codebase.
  • Local = Mac OS X
  • Prod = Ubuntu Server

What did I missed ?



via Chebli Mohamed

how to control multiple ajax requests in laravel 5.2

I am working on an application where different ajax requests fires depending upon different actions.

For example, there is a chat window having send button. When i click on that button an empty message is sent with ajax, successfully. It work nice. But when I hit the send button too many times, at start some requests respond 200 (ok) but then it respond 500 (internal server error). Due to this the other requests that are going continuously like updateLastActivity also disturb. The preview of the error in developer's tool is: Whoops like something went wrong.

Note: When I make this chat system in core PHP, it work fine. There is no internal server error when I send too may requests.

Here is the code I am using

    //the following code is used to send the message
 $(document).on('click','.send_message_bt',function(event){
     event.preventDefault();

        var id=$(this).data('id');
        var name=$(this).data('name');
        var message=$("#message_field-"+id).val();



    $.ajax({
        //headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
         headers: { 'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!} },
        url:'',
        type:'POST',
        data:{
          id:id,
        message:message
           },
        success:function(data,status){
        //clear the message field value
        $("#message_field-"+id).val('');

        //update the chat history
        fetchChatHistory(id,name);


    },
        error:function(response){
           if(response.status==401){
                  alert('You are not logged in!');
                  window.location=window.location.href;
                   }

           }

});

});

here is the back end code

public function sendMessage(Request $request){
    $message=new Userchatmessage();
     $message->message=$request->message;
     $message->sender_id=Auth::user()->id;
     $message->receiver_id=$request->id;
     $message->save();
     return response('success');
}

How to fix this issue.



via Chebli Mohamed

lundi 10 septembre 2018

is Collection a Laravel instance or PHP instance?

is collection a laravel instance or PHP instance. I always hear people say a Eloquent return a laravel collection so I want clearance on this



via Chebli Mohamed

dimanche 9 septembre 2018

Laravel: Do one query update and then, if that succeeds, do the next, otherwise, do neither

So, I want to update two different user accounts with the same value.

Scenario: User 1 transfers money to User 2:

$transfer_from = $account->decrement('balance', $amount);

$transfer_to = Account::where('user_wallet_address', $receiver_wallet_address)->increment('balance', $amount);

But, what I want, is something like this:

$account->decrement('balance', $amount)->$transfer_to;

As in if the decrement succeeds, then update the other user's balance, otherwise, both should fail

Thoughts?



via Chebli Mohamed

Where Should I place an ID which I require in all my requests? Session or Cookie or any other option.

Where Should I place an ID which I require in all my requests? Session or Cookie or any other option. please help

I am calling an API once user logedIn and it gives me an ID now I require this Id in most of the other calls. what should I Do? where to put this ID?



via Chebli Mohamed

mercredi 5 septembre 2018

Return Download Docx File in Laravel 5

I'm trying to create a url that return word doc file when user visit.


I have tried

public function resume()
{

    $file= public_path(). "/docs/John's Resume.docx";
    $headers = array(
        'Content-Type: application/msword',
        'Content-Disposition:attachment; filename="cv.docx"',
        'Content-Transfer-Encoding:binary',
        'Content-Length:'.filesize($file),
    );

    ob_end_clean();
    return Response::download($file,"John's Resume.docx", $headers);

}

I kept getting

FileException in BinaryFileResponse.php line 97:
File must be readable.

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

Force response()->download() return HTTPS url

I have switched my Laravel 5.1 to HTTPS and everything seems fine, except the file download part.

The problem is response()->download() returns a HTTP link instead of HTTPS and I get a mixed content in Chrome, so the link is blocked.

And some code:

$headers = array
            (
                'Content-Type' => 'application/vnd.android.package-archive'
            );
return response()->download(config('custom.storage') . $apk->generated_filename, $apk->filename, $headers);



via Chebli Mohamed

lundi 3 septembre 2018

vsmoraes/laravel-pdf show() function outputting codes on page

When I try to output a .pdf file using vsmoraes/laravel-pdf as below

 $pdf
     ->load($html)
     ->filename($booking->ReservationNumber . ".pdf")
     ->show();

I am getting an output like below:

enter image description here

This happens only in production environment and it's working fine in my local development environment, what could be the issue here?



via Chebli Mohamed