jeudi 30 novembre 2017

laravel perform two query in one function

Simply i have a two table

GALLARIES AND MEDIA

In a GALLARIES table id,title,venueId i have saved gallary folder name for the particular venue. In MEDIA Table I have id,imagepath,is_thumb(0 or 1),gallery_Id

What i want to do is when i set is_thumb_image(1) then i have call two function

1 st for unset image all with gallery_id and after i call second function for set is_thumb_image for particular image.

Is it possible to call one function only and perform both functionalty.

Here is my Controller code.

        $albumId = $request->album_id; //table galleries id  - album name
        if($request->is_thumb_image == "true") { 
            $media1->UnsetThumbImage($albumId); // first unset thumb_image 
            $media->setThumbImage($media->id); // call for set thumb_image 
        } else {
            $request->is_banner_image = false;
        }

Here is my model functions

 public function setThumbImage($mediaId) {
   try {
        DB::table('media')
            ->where('id', $mediaId)
            ->update(['is_thumb_image' => 1]);
        $this->is_thumb_image = 1;
    } catch (\Exception $ex) {
        echo $ex->getMessage();
        dd($ex->getTraceAsString());
    }
}

public function UnsetThumbImage($albumid) {
    DB::table('media')
    ->where('gallery_id', $albumid)
    ->update(['is_thumb_image' => 0]);
    $this->is_thumb_image = 1;
}

How can i do it calling only one function.



via Chebli Mohamed

how can delete record using db class with softdelete ? can we do?

I Want to delete record using db class but not delete physically delete. I want to softdelete using db class. Is it Possible? My Code is $items =DB::table('forum')->where('forum_id', '=', $forum_id)->softDeletes();



via Chebli Mohamed

December month date query not working in Laravel

Very bizarre one here, I have a controller doing a date search for the current month - December in this case.

I have two dates for the range of December - I'm using created_at >= date(2017-12-01) and created_at < date(2018-01-01).

In Laravel the query it is not returning any results at all even though a) I'm expecting some records, and b) mysql query select * from redemptions where created_at >= date('2017-12-01') and created_at < date('2018-01-01') order by created_at desc, gives me the results I expect.

In the controller I have verified via dd that both the dates are as above and the sql dump is correct: select * from redemptions where created_at >= ? and created_at < ? order by created_at desc.

Hope I'm not missing something obvious :)



via Chebli Mohamed

Syntax to copy a file in Laravel (5.4) from local to AWS S3?

What's the best way to copy an uploaded file from my Laravel installation (running on Heroku) to S3? I can't do a direct to S3 upload, as it's an image that I'm locally generating a thumbnail for. I also don't want to use any extra libraries etc. (sledgehammer to crack a nut etc.). File needs to go in a particular folder in my S3 bucket. Is this the only/best way? :-

Storage::disk('s3')->put('S3_folder_name/file.jpg', file_get_contents('my_local_file.jpg'));

Thanks



via Chebli Mohamed

Laravel 5.4 printing out a seating plan

I have an sql table of seats with the columns (id,row, seat_number). Im trying to print out the seats something like this,

A 1,2,3
B 4,5,6
C 7,8,9

I've managed to do this by hard coding if statements for each row, like so

    @if($row->rw==='A')
                  <div class="row">
                      <div class="col-md-1"></div>
                     @foreach($seats as $seat)
                         @if($seat->rw === 'A')
                             
                        @endif
                @endforeach
            </div>
        @endif

What I would like to know is a better method that doesn't require me to hard code each row. I'm guessing it would be some loop that would go through and check the row for unique character and print the seat_numbers in that row.

I'm fairly new to laravel and php as I'm sure you can tell, I don't want anyone to do the work for me I just want pointing in the right direction. Any help is greatly appreciated.



via Chebli Mohamed

Laravel 5.5 Inconsistent JSON when using filter on a collection

I am building a simple search for a project I am working on. It works fairly well for the most part. I am running into an issue when using ->filter(function($item) { .. }).

Here is the code:

$users = App\User::select(['id', 'username', 'preferred_first_name', 'preferred_last_name'])
        ->where('username', 'like', $like)
        ->orWhere('preferred_first_name', 'like', $like)
        ->orWhere('preferred_last_name', 'like', $like)
        ->orWhere('id', $query)
        ->get();
$users = $users->filter(function($item) {
    return !$item->is_terminated();
});
return UserResource::collection($users);

And here is the toArray function in UserResource:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'username' => $this->username,
        'full_name' => $this->full_name,
    ];
}

The issue I am having is some of the JSON is returned in two different formats:

Format A: { data: [ {..}, {..}, .. ] }
Format B: { data: {"0": {..}, "1":{..},..} }

I would like all the JSON to be returned in Format A all the time. I've narrowed it down the filter() function. But it is inconsistent. On the search term san it returns in Format B but on the term pha it returns in Format A. If removed everything works perfectly and is returned in the proper format (Format A).

If there's any code missing that could help let me know as I am unsure what needs to be included.



via Chebli Mohamed

Laravel / VueJS 403 despite hardset true values

I've got an SPA where I'm using Laravel 5.5 as the framework and VueJS in the frontend. I've installed passport but am unsure whether I've done it properly as the documentation seems to go a little bit over my head.

Any post requests that attempt to verify the user through laravel's policies are returning back 403. Even when I hard code a true response through the Policy I still return a 403? The framework and SPA are on the same domain.

Process flow:

axios.delete('/api/barracks/reply/delete/' + this.reply.id, {
   id: this.reply.id
});

-> Which processes through here in my Routes/API

Route::delete('/barracks/reply/delete/{reply}','ForumRepliesController@destroy');

Which then goes here:

public function destroy(ForumReply $reply)
{
    $this->authorize('update', $reply);
}

Which then goes through this:

public function update(User $user, ForumReply $forumReply)
{

    return true;

}

It returns a 403 error. What is also strange is that if I manually try to do the validation with something like an Auth::id()==$reply->id logic it fails because the Auth::id is null??? However in a create method it's able to correctly insert auth()->id() for the same controller.



via Chebli Mohamed

laravel Job / Queue not been processed weird infinite loop

I'm trying to create a queue but it doesn't work when I run php artisan queue:work all I get in my terminal is

[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV
[2017-11-30 19:56:27] Processing: App\Jobs\ProcessCSV

It's like an infinite loop. The id in my jobs table just goes up and up too. It does work on my laptop but not on my desktop which is very strange. I put in onto my devleopment server and it doesn't work on there either.

My code is below and any help would be appreciated.

Controller

public function upload(Request $request) {
        if($request->file('imported-file')) {

            $user = "craig@boldy.co.uk";

            $file = $request->file('imported-file')->store('uploads', 'public');
            $this->dispatch(new ProcessCSV($file, $user));

            Session::flash('success', 'Your file was uploaded successfully. We will email you once the locations have be imported.');
            return back();

        } else {

            Session::flash('error', 'Please select a file to upload!!!!');
            return back();

        }

    }

Job

public function handle()
    {

        $data = Excel::load($this->file, function($reader) {})->get();

        $apiKey = '';

        foreach($data as $row) {

            if(!empty($row['postcode'])) {

                $url = "http://ift.tt/1jxG3tJ".urlencode($row['postcode'])."&region=uk&key=";
                $tmp = file_get_contents($url);
                $xml = simplexml_load_string($tmp);

                // print_r($xml); exit;

                if((string)$xml->status == 'OK' && isset($xml->result[0])) {

                    if(isset($xml->result[0]->geometry->location->lat)) {
                        $lat = (string)$xml->result[0]->geometry->location->lat;
                    }

                    if(isset($xml->result[0]->geometry->location->lng)) {
                        $lng = (string)$xml->result[0]->geometry->location->lng;
                    }

                }

                Import::updateOrCreate(
                    [
                        'sitecode' => $row['sitecode']
                    ],
                    [
                        'sitecode' => $row['sitecode'],
                        'sitename' => $row['sitename'],
                        'address_1' => $row['address_1'],
                        'address_2' => $row['address_2'],
                        'address_town' => $row['address_town'],
                        'address_postcode' => $row['postcode'],
                        'charity' => $row['charity'],
                        'latitude' => $lat,
                        'longitude' => $lng,
                        'approved' => 1
                    ]
                );

            }

        }


    }



via Chebli Mohamed

how can update date in many to many relationship laravel

Can anyone help me on how to update many to many relationship? I have tasks, user can have many tasks and task can have many users (many to many), What I want to achieve is that in update form admin can assign multiple users to specific task. This is done through html multiple select input

this is my controller

public function index()
{
    // this is in main view
    $tasks=Task::all()->load('users');
    $userLogin_id=Auth::user()->id;
    $users=User::all()->where('id','!=',$userLogin_id);
    return view('adminUser.index',compact('tasks','users'));
}


public function store(Request $request)
{
    // to create new task and for who it
    $task =Task::create($request->all());
    $userId=$request['employee'];
    $task->users()->attach($userId);
    return back();
}

public function edit($task_id)
{
    //to go to view that has update code
    $task=Task::find($task_id)->load('users');
    $userLogin_id=Auth::user()->id;
    $users=User::all()->where('id','!=',$userLogin_id);

    return view('adminUser.edit',compact('task','users'));
}

public function update(Request $request, $task_id)
{
    //to update task 
    $user_id=$request['employee'];
    Task::where('id',$task_id)
        ->update(['title'=>$request['title'],
                    'description'=>$request['description'],
                    'status'=>$request['status'],
                    'file_path'=>$request['file_path']]);
    //what i can do complete this method if it is correct
    return redirect('/admin');
}

this my user model

public function tasks(){
   return $this->belongsToMany('App\Task','Todos','user_id','task_id');
}  

this my task model

public function users(){
    return $this->belongsToMany('App\User','todos','task_id','user_id');
}  



via Chebli Mohamed

Submit DataTables Selected Value to PHP Deletion function in Laravel via a Post Request

I have a table, using the DataTables API, that is populated with a list of entries from a database. I would like my user to select a entry from the table, click a delete button, and the selected entry will be deleted from the database. I'm using Laravel. So, my initial instinct is to send the selected entry in a post request where I will process the selected entry via a Controller.

1) How can I forward my selected entry (var rowData) to my Laravel Controller via a post request once the user clicks the delete button?

2) Is there a better solution?

[HTML]

<div class="table-responsive">
    <table class="table table-bordered" width="100%" id="someTable"></table>
</div>

<form action="/somePage/deleteObject" method="post">
    <input type="hidden" value="delete">
    <button id="delBtn" type="submit" class="btn" >
        Delete
    </button>
</form>

[Javascript] - Populates table and provides events for when an entry is selected.

<script type="text/javascript">
    $(document).ready(function(){ 
        var table = $('#someTable').DataTable( {
            select: {
                style: 'single'
            },
            "scrollX": true,
            "scrollY": '70vh',
            "scrollCollapse": true,
            "paging": false,
            dom: 'ft',
            "aoColumns": [
                { "sTitle": "Name",  "mData": "name" },
                { "sTitle": "Email", "mData": "email" },
                { "sTitle": "Group", "mData": "group" },
                { "sTitle": "Access Level", "mData": "level" }
            ],
            "aaData": {!! collect($users)->toJson() !!}
        } );

        // Event handling: Pulled directly from DataTables example
        table
            .on( 'select', function ( e, dt, type, indexes ) {
            document.getElementById("delBtn").disabled = false;
            var rowData = table.rows( indexes ).data().toArray();
        } )
            .on( 'deselect', function ( e, dt, type, indexes ) {
            document.getElementById("delBtn").disabled = true;
            var rowData = null;
        } );
    } );
</script>

[Laravel Route]

Route::post('/somePage/deleteObject', 'Controller_Page@deleteObject');

[Laravel Controller]

public function deleteObject(){
    $value =  Request::get('rowData');
    dd("Reached Delete", $value);
}



via Chebli Mohamed

Attain many has-many-through

I need to attain latest comments from array of users through posts.

Users model

public function comments()
 {
   return $this->hasManyThrough('App\Comment', 'App\Post');
 }

has-many-through

$user = users::where('id',5)->first();

$user->comments()->get()

many has-many-through

$user = users::where('role','member')->get();

How can I achieve this.



via Chebli Mohamed

Laravel DB class no table method on new project

I just can't figured out this issu; On a new Laravel project, I just can't use table method on DB class.

I use PhpStorm as EDI on OSX Sierra with Laravel 5.5.

Here my steps:

  1. In terminal: Laravel new testproject
  2. In terminal: composer install
  3. In terminal: php artisan make:controller testdummy
  4. In EDI:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;
    
    class testdummy extends Controller
    
    {
        //
        public function index(){
            DB::table('title')->insert([
                'label' => 'test1',
                'desc' => 'test2',
            ]);
        }
    }
    
    

The 'table' have a warning popup in EDI that say:

'Method table not found in Illuminate\Support\Facades\DB'.

And no insertion are made to database.

Have you some hints on where to look next to help me find the problem?

thanks,



via Chebli Mohamed

php code to get the device OS and version?

I am making an Android app with a mechanism that requires getting the device OS and version. I was hoping that you will give me an answer.

ps: working on laravel 5 with php 7.1



via Chebli Mohamed

Mysql: How to optimize deleting thousands of rows

I have hundred thousand rows in my table and I want to delete with condition It took 15 min but still not done? It's just a plane table no related model. Its a chunk of almost 200k rows that I want to remove I need to specify which needed to remove so I need to use condition If I can just truncate. Is there any way to handle this, I'm using laravel

Details::where('file_name_belongs',$file_name)->delete();



via Chebli Mohamed

Displaying the correct datetime value in laravel

I have a blog created with Laravel 5.5, In PostController and in Create function i have specified the time format for "Published_at" cloumn to 24 format, and it's inserted correctly into database with the right format

Nov 30, 2017 | 17:11:19

But when i try to display the time in post page i got this format

30, 11, 2017 | 1:51:29 pm

I don't know why, i have tried to use "strtotime()" solution but i got wrong date and time

Jan 1,1970 | 01:00:00

I hope the problem clearly described



via Chebli Mohamed

Laravel - Weird Invalid date time format error when updating post

I am making an edit page to edit posts on my website, Each post is inside of a channel. When I try to edit the post without changing the channel it is in. It gives me a weird error stating:

Invalid DateTime format: 1366 Incorrect integer value: 'PHP' for column 'channel_id' at row 1

But however, When I edit the channel too, It works perfectly fine. What is causing this? I think it has something to do with my form. A post has a channel_id. so that connects it to a channel with that ID. The relations between the two is fine.

This the the piece of form that I think is causing the issue:

<div class="form-group row">
   <div class="col-md-12">
      <label for="Kanaal">Kanaal:</label>
   </div>
   <div class="col-md-12">
     <select class="form-control" id="Kanaal" name="channel_id">
       <option selected></option>
       @foreach($channels as $channel)
       <option value="" >
       
       </option>
       @endforeach
     </select>
   </div>
 </div>

The method where I store the updated post looks like this:

public function updatePost(Request $request, $id)
{

    $post = Post::find($id);
    $post->channel_id = $request->channel_id;
    $post->title = $request->title;
    $post->text = $request->text;
    $post->slug = str_slug($request->title);

    $post->save();

    return back()->with('flash', 'Het bericht is bewerkt!');
}

It reaches the method just fine. But when I do not edit the channel option tag it gives me that error, While if I do edit it, it works fine.

I don't know if I'm explaining this well, But this is the best I can do. Thanks in advance!



via Chebli Mohamed

Can't querry datas

I have the following tables:

biens(id,prix,option_id,quartier_id,typebien_id);
options(id,libelle);
typebiens(id,libelle);

I need to select all biens with the specific optionsand typebiens. here is what i do:

    public function afficherCommerce($libelle)
    {
       $bienscommerce = \App\Bien::with(['option','typebien','quartier'])
           ->where('biens','option.id','=','biens.option_id')
           ->where('options.libelle','=',$libelle)
           ->get();
}

But can't query them. Need your help!



via Chebli Mohamed

laravel-localization with translated slug stored in database

I try to make a multilingual laravel. To do this, I use different packages

My slugs are translated and stored in database as follows:

{
   "fr": "Accueil",
   "en":"Home"
 }

And all my other translatable data are also like that. And to access one of my data, I use for example, $page->slug or $page->title.

My translations work well. But now, I'm trying to build a menu of languages with the right URLs.

I want, if I am on the page "about" have two links in the menu :

  • http://myapp/en/about
  • http://myapp/fr/a-propos

Here is my code :

<ul>
    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a rel="alternate" hreflang="" href="">
                
            </a>
        </li>
    @endforeach
</ul>

Unfortunately my urls are bad. If I am on the page "about" in English I have in my menu :

  • http://myapp/en/about
  • http://myapp/fr/about

And I would like http://myapp/fr/a-propos. The data is stored in my database.

Is there a way to make sure to collect data from other languages while in a different locale (here I am in EN and I would like to have the slug FR).

Can you help me ? Thank you very much !



via Chebli Mohamed

Laravel 5 validate string with multiple dates comma separated

How can i validate this string with the laravel validate? I want to check if the dates between the commas is a date.

2017-11-11,2017-12-11-2017,2017-13-11



via Chebli Mohamed

Larave5 permissions issue

I have a simple ansible script to up and run docker environment for local/development machines. Inside the script I have set project permissions task which caused the problems:

One version of the task:

- name: Set permissions
  shell: >
      sudo chown -R :  && sudo chmod ug+w -R 
      && sudo chgrp -R www-data /storage /bootstrap/cache
      && sudo chmod -R ug+rwx /storage /bootstrap/cache

and all working fine until we need to store/change something in storage directory. i.g we can't log command line information.

Another version:

- name: Set permissions
  shell: >
      sudo chown -R : 
      && sudo find  -type f -exec chmod 664 {} \;
      && sudo find  -type d -exec chmod 775 {} \;
      && sudo chgrp -R www-data /storage /bootstrap/cache
      && sudo chmod -R ug+rwx /storage /bootstrap/cache

the issue I'm facing here is when I running npm run dev from my user I got the error:

> @ development /var/www/vhosts/project
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

sh: 1: cross-env: Permission denied

npm ERR! Linux 4.2.0-42-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "development"
npm ERR! node v6.11.5
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 126
npm ERR! 
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs 
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls 
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/www/vhosts/project/npm-debug.log

npm ERR! Linux 4.2.0-42-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
npm ERR! node v6.11.5
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @ dev script 'npm run development'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run development
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs 
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls 
npm ERR! There is likely additional logging output above.

FYI: npm install working fine

I would appreciate any help!



via Chebli Mohamed

how to create sub page in laravel 5.5?

I am working in laravel 5.5 and I am trying to open page from route like

Route::get('/admin/admin/adminprofile', function() {   return \View::make('admin\adminprofile');});

but it is not working.



via Chebli Mohamed

Laravel Media Gallary Function not Working

This is my first question on stack.Here my question is i have function saveMedia, On this function i have save media Images and also set flag is_banner_image or is_thumb_image.When i upload two images and set one image as thumb image it update on table both images as thumb_image. I have added my Controller function here..

public function saveMedia(Request $request) {
    $albumId = $request->album_id;

    try {
        $gallery = Gallery::findOrFail($albumId);
        $media = $gallery->media()->findOrNew($request->id);
        $media->fill($request->all());

        if($request->is_banner_image) { // true or false
            $media->setBannerImage();
        } else {
            $request->is_banner_image = false;
        }

        if($request->is_thumb_image) { // true or false
            $media->setThumbImage();
        } else {
            $request->is_thumb_image = false;
        }

        if($media->save()) {
            return response()->json([
                'id' => $media->id,
                'message' => 'Media saved successfully'
            ]);
        } else {
            return response()->json([
                'message' => 'Unable to save media!!'
            ]);
        }
    } catch (\Exception $ex) {
        return response()->json([
            'message' => 'Unable to save media!!'
        ]);
    }
}

My Model Query function for both thumb image and banner image :

public function setBannerImage() {
    try {
        DB::table('media')
            ->whereIn('gallery_id', $this->gallery->source->gallery->modelKeys())
            ->update(['is_banner_image' => 0]);
        $this->is_banner_image = 1;
    } catch (\Exception $ex) {
        echo $ex->getMessage();
        dd($ex->getTraceAsString());
    }
}

public function setThumbImage() {
    DB::table('media')->
        whereIn('gallery_id', $this->gallery->source->gallery->modelKeys())->
        update(['is_thumb_image' => 0]);
    $this->is_thumb_image = 1;
}

I want to update only one at a time.Thanx in advance.



via Chebli Mohamed

Laravel: Prevent direct access of files from public folder

I am stuck on this part of my laravel application, Where I am asked to protect the files from directly accessed via url browser hit. I have a public folder in which in a doc folder is present where all the documents are going to be uploaded. I just need a solution to prevent this where i can access docs directly from my application but any third party visitor can not view my docs (images,pdfs etc..).

I have tried many solutions but its not at all working. I just want to things :- 1. Protect my docs through direct access. 2. Way of implementing it in laravel (via .htaccess)

I know this can be possible through htaccess, but how? Kindly help Please :)



via Chebli Mohamed

How To Design Weekly Hours For a lot of Users and show as Yearly Report

Please Help Me To Store Weekly Hours Of Employee Data iN mysqli weekly wise



via Chebli Mohamed

Which is best way to call model function in controller with multiple where condition using Laravel ?

  • Create function in model with multiple where condition
  • Possibility to use group by with aggregate (Multiple group by as well)
  • Use whereIn
  • Use Order By

I mean make it dynamically as more you can

Also explain how we can call in controller by using load model first.



via Chebli Mohamed

Migrating from Laravel 4.2 to 5.5 (Authentication / Password Mismatch Error)

I am migrating a project from 4.2 to 5.5. I have reached 5.3, I have taken backups for every successful version update 5.0, 5.1, 5.2. The problem is, after my 5.2 update, my authentication as working well and I was able to login to the system. However, after the 5.3 update, I am not able to login. I have followed all steps from official documentation for upgrading.

Thanks in advance for any help.



via Chebli Mohamed

Page Expired if POST method (Laravel 5.5)

My routes

Route::middleware('auth.basic')->group(function(){


Route::post('/', 'DeliveryController@calc')->name('delivery');

Route::post('pickup/', 'DeliveryController@getPickup');

Route::post('pec_pickup/', 'DeliveryController@getPecPickupPoint');});

when i try send request with postman i got "Page Expired". But if i replace all routes with GET - all ok.



via Chebli Mohamed

check the object is created and create new one if not exist

I want to create a object to insert a new data or update the value.I want to check the object is created and then create a new object.before create a object I want to check exit or not

$status_tracker=new status_tracker();   



via Chebli Mohamed

MySQL: Specified key was too long; max key length is 767 bytes

I'm creating a development version of a Laravel 5.4 application, which is working, albeit without a complete database.

When I ran php artisan migrate it generated most of the tables, but some failed, though without errors.

When I then attempted an import via phpMyAdmin, I got an error:

#1071 - Specified key was too long; max key length is 767 bytes

... on a number of tables, which happen to be the ones the migration failed to create (it's worth noting that some of the tables have multiple keys, so the error itself is — to me at least — a bit vague).

The production application uses MySQL 5.7 while the development application uses 5.6, which I understand is the cause.

Anyone know how I get around this, without using Docker?



via Chebli Mohamed

storing file path using laravel and component vuejs2

i work with an interface with backend laravel and frontend vuejs2 i used a component to register a new record in my database it work perfectly with the input type text but with input type file i don't know how to get the path and store it using function store of laravel

component vuejs

template

  <input type="file" @change="processFile($event)"  id='image' v-model="article.image" >

</div>
 <div class="modal-footer">

<button type="button" @click="CreateArticle">Enregistrer</button>
 </div>

vue Script

<script>
    export default {
        data(){
            return {
                articles:[],

                article:{
                    image:'',
                },
          }
        },


        methods:{


            CreateArticle:function(){

                axios.post(window.Laravel.url+'/addArticle',this.article)

                .then( response => {
                    if(response.data.etat){

                        this.article.id=response.data.id;
                        this.articles.unshift(this.article);
                        this.article={
                                    id:0,
                                    image:'',

                                }     
                    }

                    })

                  .catch(error => {


                    });
            },

           processFile(event) {
            this.someData = event.target.files[0],

  },
        },

    }
</script>

Controller function

public function addArticle(Request $request){

        $art=new Article();
        if($request->hasFile('image')){
         $art->img=$request->image->store('images');

       }

        $art->save();

    return Response()->json(['etat'=>true,'id'=>$art->id]);

}

route:

Route::post('/addArticle','CategorieController@addArticle');



via Chebli Mohamed

How to implement query caching in laravel

I am trying to implement caching in my php/laravel application. I am using the repository pattern along with laravel. Now laravel provides inbuilt cache support something like

$value = Cache::rememberForever('users', function() {
    return DB::table('users')->get();
});

But i wanted to implement a general cache system so that even if i change my database this should work. Any help is appreciated.



via Chebli Mohamed

mercredi 29 novembre 2017

Laravel Download Database Tables in background

I've created command in Laravel which download (copy) database's .sql files from staging server and paste it on production server (Requirement). I don't have SSH access to production server, So created route for that command and execute it from URL. Here are my code.

Route

Route::get('console/import_all',
    function () {
    Artisan::call('importDatabase:staging', ['tables' => 'all']);
});

Command Function

private function downloadFile($url, $path)
{
    sleep(5);
    return copy($url, $path);
}

Now there are approx 30+ files and some of them are more than 10MB in size. My command works fine from SSH (by admin) and from URL as well. But issue is when I hit command from URL, page keeps loading till all download finish. Is there any way to execute this from background? So if admin hit button from admin panel, s/he should not wait for all the time until coping all file finish and I can display message that process has been start and you will notify once done.



via Chebli Mohamed

local.ERROR: PDOException: SQLSTATE[HY000]: General error: 1615 Prepared statement needs to be re-prepared in happen in every morning

I am very new to laravel,

Now handling a laravel project it's get error in every morning, and after some time it's become okay. I don't understand what is the issue. I googled it and see some similar issues. But it does not resolve my issue guys help me to find solution for this. It's cause of big time lose for my work.

db version is 5.1.1



via Chebli Mohamed

Laravel / Eloquent - Prevent "deleted_at" Column From Being Returned by get() Method

I have a model that looks like:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Location extends Model{

    use SoftDeletes;

    // Name of our database table
    protected $table = 'locations';

    // Column for soft deletes
    protected $dates = ['deleted_at'];

    // Columns that are mass assignable
    protected $fillable = ['name', 'address', 'city'];

}

When I call Location::get(), the deleted_at column is returned by default.

How do I prevent this column from being returned without explicitly specifying it?



via Chebli Mohamed

Call to undefined method Illuminate\Database\Query\Builder::attachPermission()

Here's my code for DatabaseSeeder

use Illuminate\Database\Seeder;
use App\User;
use App\Role;
use App\Permission;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
       // $this->call(UsersTableSeeder::class);
       DB::table('users')->delete();
       //1) Create Admin Role
       $role = ['name' => 'super-admin', 'display_name' => 'Super Admin', 'description' => 'Full Permission'];
       $role = Role::create($role);
       //2) Set Role Permissions
       // Get all permission, swift through and attach them to the role
       $permission = Permission::get();
       foreach ($permission as $key => $value) {
           $role->attachPermission($value);
       }
       //3) Create Admin User
       $user = ['name' => 'Super Admin User', 'email' => 'superadminuser@test.com', 'password' => Hash::make('superadmin')];
       $user = User::create($user);
       //4) Set User Role
       $user->attachRole($role);
    }
}

While I'm using below command for db seed i get an error saying Call to undefined method Illuminate\Database\Query\Builder::attachPermission(). I know this is common question in the forum but i don't know what's wrong in my code.

php artisan db:seed --class=DatabaseSeeder



via Chebli Mohamed

Make active class for parent and subs in Laravel

I have menu like this:

<li class="treeview">
        <a href="#"><i class="fa fa-comment"></i> <span>Comments</span>
            <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
            </span>
        </a>
        <ul class="treeview-menu">
            <li><a href="http://ift.tt/2Agdbqz">All Comments</a></li>
            <li><a href="http://ift.tt/2AkbDti">My Comments</a></li>
            <li><a href="http://ift.tt/2Ae7skW">Approved</a></li>
            <li><a href="http://ift.tt/2AkbF4o">Disapproved</a></li>
        </ul>
    </li>

All i want is when i click on submenu for example "My comments" menu, the Comments menu and My Comments active will have a class like this

    <li class="active"><a href="#"><i class="fa fa-comment"></i> <span>Comments</span></a></li>
    <li class="active active-sub"><a href="http://ift.tt/2AkbDti">My Comments</a></li>

so how can i make this can be happen? Thanks



via Chebli Mohamed

search box using GET method

I have a small practice project in Laravel 5.5 I would like to implement a search filter but I do not understand how to apply it. I would like a help. Thank you



via Chebli Mohamed

How to filter results in Laravel using Eloquent Models

I am attempting to use the following

$orders = \App\Order::with([
    'Customer' => function ($query) use ($filterFirst, $filterLast, $filterstate)
    {
        if($filterFirst)
        {
            $query->where('customers.first', 'LIKE', "{$filterFirst}%");
        }
        if($filterLast)
        {
            $query->where('customers.last', 'LIKE', "{$filterLast}%");
        }
        if ($filterstate)
        {
            $query->where('customers.state', '=', $filterstate);
        }
    }

However, when I run ->get on $orders I get the entire table of orders, and I just want to get the orders that match the Customer Filters...

Any ideas on how I can accomplish this?



via Chebli Mohamed

Inject Route Action on Controller

I've made a role middleware to check if user has a specific Role:

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user() === null) {
            return response("Insufficient permissions", 401);
        }
        $actions = $request->route()->getAction();
        $roles = isset($actions['roles']) ? $actions['roles'] : null;
        if ($request->user()->hasAnyRole($roles) || !$roles) {
            return $next($request);
        }
        return response("Insufficient permissions", 401);
    }
}

If I want to check for some role in a specific role it's easy. I only have to add the middleware and an additional action called roles. E. g.:

Route::get('payments/{id}/pay', [
    'uses' => 'PaymentController@aprove',
    'as' => 'payments.aprove',
    'middleware' => 'roles',
    'roles' => [User::ADMINISTRATOR, User::SPOT_MANAGER, User::SELECTION_PROCESS_MANAGER],
]);

Doing this way works as expected. However, I have some routes that are Route::resource instead of get, post, or something like this. Laravel don't allow for specifying roles => [...] in resource.

The documentation says that if I want to inject middleware on resources I should do this on controller. But I can't specify roles => [...] as I used to do in normal routes anywhere! How could I do this?

Thanks in advance.



via Chebli Mohamed

How to count checkboxes using jQuery?

I'm doing a dashboard in Laravel 5.4, and I have a table with several checkboxes. I need to count each time 1 is selected and show the result on the side.

Basically I have to count in real time. And I have 2 lines, I have to count them separately, so I have separate classes

I've tried some things but nothing works.

Thanks in advance for help and ideas on how I can do this, below I leave the code of my checkbox.

{!! Form::checkbox('dente[]', $dente->id, null, ['class'=>'denteCheck-up'] ) !!}

{!! Form::checkbox('dente[]', $dente->id, null, ['class'=>'denteCheck-down'] ) !!}

In jquery, I've tried +/- this

$('.denteCheck-up').change(function(){ });

$('.denteCheck-down').change(function(){ });

I'm trying to get the result to appear here

<td id="count_dentes_up"></td>

<td id="count_dentes_down"></td>



via Chebli Mohamed

In Laravel Eloquent create method I am not able to save the data in database

I have Three models:

  • Language
  • Article
  • Category

The Article table has two foreign keys category_id and Language_id. Language-Model has "One to Many" Relationship with Article-Model, Similarly Category-Model has "One to Many" Relationship with Article-Model.

My Category model:

class Category extends Model
            { 

            protected $fillable = [
                 'category_name', 
            ];

            public function articles(){

                return $this->hasMany('App\Article');
             }
           }

My Language model:

class Language extends Model
    {
         protected $fillable = [
            'language_name'
        ];

         public function articles(){

            return $this->hasMany('App\Article');
        }

    }

My Article model:

class Article extends Model
{
 protected $fillable = [

   'language_id','category_id','category_name','article_title',
   'article_desc','source_from','source_url','video_link',
   'audio_url','author_name','article_image_url','like_count'
    ];

    public function languages(){

        return $this->belongsTo('App\Language');
    }

    public function categories(){

        return $this->belongsTo('App\Category');
    }

}

How can I insert in the database using Laravel Eloquent?

 $Article = new Article (
                 [
                   'article_image_url' => $img_url ,
                   'audio_url' => $audio_url,
                   'category_name'=>$category_name ,
                   'article_title'=>$request->article_title,
                   'article_desc'=>$request->article_desc,
                   'source_from'=>$request->source_from,
                    'source_url'=>$request->source_url,
                    'video_link'=>$request->video_link,
                    'author_name'=>$request->author_name,
                    'like_count'=>'0',

                  ]
            );

            $language = new Language;
            $category = new Category;
            $language->articles()->save($Article);

language_id doesn't have a default value; it is foreign key.



via Chebli Mohamed

Laravel: How to use `Can` middleware

I want to give users that are logged in and are of a specific type (leader) access to all pages handled by a controller.

In AuthServiceProvider I created the following Gate

Gate::define('isLeader', function ($user) {
  return $user->isLeader();
});

Inside the controller that is only for logged in leaders, I have the following constructor

public function __construct()
{
    $this->middleware('auth');
    $this->middleware('can:isLeader');
}

For users who are a leader this works. But for users who are not a leader I get the error message This action is unauthorized. when accessing a page through this controller:

enter image description here

Instead of throwing an error message I would rather redirect the user to home if he is not a leader. How can I achive this?



via Chebli Mohamed

how to save data to pivot table in laravel 5.5?

I have 4 tables:

advertises
id, title, description, thumbnail, category_id, subcategory_id
categories
id, name
subcategories
id, name, category_id
category_subcategory
cateogory_id
subcategory_id

I want to create and save an advertise with its category and subcategory, for example: advertise title: buy a phone with javascript i display a category which is in this case electronics, and the category electronics has subcategories: buy, sell. the user selects the buy subcategory so the advertise will be like this: buy a phone->electronics->buy. now i save the category_id and the subcategory_id in the advertise table, but there are many categories that have the subcategories buy and sell. the subcategory table row looks like:

id, name, category_id
1, buy, 1
2, sell, 1

how to save the data in the database? and how to retrieve the the advertise?

I made an image gallery for each advertise, I made a function that uploads an image to an advertise like a thumbnail, and another function that uploads the other images when you access the edit route, but i want the user to be able to upload more photos when he creates the advertise not after the advertise is created. the images are saved in a separated table:

images
id, name, advertise_id

how to save the images when the user creates the advertise?

this is the advertise model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Advertise extends Model
{
    protected $fillable = ['title', 'description', 'image', 'price'];

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

    public function category()
    {
        return $this->belongsToMany('App\Category_Subcategory');
    }

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

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

    public function image()
    {
        return $this->hasMany('App\Image');
    }
}



via Chebli Mohamed

get only one row from first table in table left join in laravel

I have two table 1. Bog_post 2. blog_image

Now I want only one image from blog_image table. I also save blog id in blog_image table. how can i do this query in laravel ?



via Chebli Mohamed

Laravel: Product Update/ Method update does not exist

Trying to update my Auth:user() Product with update method, but always results in Error. User has many products() / Product belongsTo user().

$this->validate($request, [

            'title'=> 'max:140',
            'brand'=> 'max:140',
            'sku'=> 'max:140',
            'description'=> 'max:140',
            'price'=> 'max:140',
            'availability'=> 'max:140',

        ]);

        $product = auth()->user()->products()->findOrFail($id);

        $product->update([

            'title' => $request->input('title'),
            'brand' => $request->input('brand'),
            'sku' => $request->input('sku'),
            'description' => $request->input('description'),
            'price' => $request->input('price'),
            'availability' => $request->input('availability'),

        ]);

Am I missing something within my Controller? Btw.

Auth::user()->products()->update([
            'title' => $request->input('title'),
            'brand' => $request->input('brand'),
            'sku' => $request->input('sku'),
            'description' => $request->input('description'),
            'price' => $request->input('price'),
            'availability' => $request->input('availability'),
]);

updated every User related product to the same values.

So the problem is within the Product specification.

Any suggestions? Thank you



via Chebli Mohamed

Laravel connect to Cloud Database no works

my problem is i have laravel APP on my Local Enviroment and i m trying to connect to Cloud based mysql server

Laravel 5.5

i changed my .env file

example :

DB_HOST=46.229.230.***
DB_PORT=3306
DB_DATABASE=name
DB_USERNAME=nameuser
DB_PASSWORD=passuser

but i getting this error and idk why it trying to loggin to 158..... server is restarted database 100% working connect with mysqli works perfect

SQLSTATE[HY000] [1045] Access denied for user 'nameuser'@'158.193.105.***' 

any help ?



via Chebli Mohamed

Laravel PHP : How to get Specific Column ID when we apply joins on 3 tables?

I want to get the Rating table ID , but in my jason then will give me the attributes table id when we apply this joins, MY QUERY:

$search = \Request::get('q');
    $u_id = User::find($id);

        $records = DB::table('ratings')->where('user_id' , $id)-
 >where('user_id' , $id)->where(function($q) use ($search){
             $q->where('attribute' , 'like' , '%' .$search. '%');
             $q->orwhere('score' , 'like' , '%' .$search. '%');
             $q->orwhere('attrtype' , 'like' , '%' .$search. '%');
        })
        ->join('users','ratings.user_id','=','users.id')->join('attributes' 
, 'attributes.id' , '=' ,'ratings.attribute_id' )->Paginate(5);
dd($records); 
return view('employee.show',compact('records' , 'u_id' , 'search')); 

After this we Get the ID of Attribute table ,Like That

But we get the Rating tables ID , Thanks Developers in advance.



via Chebli Mohamed

laravel collection is 'broken' (strange dots)

I faced this problem before, but couldn't find out the reason. I use laravel 5.5 and php7.0 . I'm fetching data from excel file(about 400 lines) with this excel package(it takes a little bit long to execute the string). the problem is, when I got the collection of data, its kinda 'broken'. enter image description here what does this mean? I'm sure its not about the package, I had similar problem before when I was making API request, it seems like this problem happens only with big amount of data. can someone explain why this happens and how should fix it? here's my file fetching method

public function index()
{
    \Excel::load('uploads/data.xlsx', function($reader) {
        $results = $reader->all();

        dd($results->all());
    });
}



via Chebli Mohamed

Laravel Model->get returns 502 Bad Gateway

I am running Laravel 5.x with valet on OS X...

When I execute the following query, I get the response I am looking for...

$orders = \App\Order::with([
    'Customer' => function ($query) use ($filterFirst, $filterLast)
    {
        if($filterFirst) {
            $query->where('customers.first', 'LIKE', "{$filterFirst}%");
        }
        if($filterLast) {
            $query->where('customers.last', 'LIKE', "{$filterLast}%");
        }
        return $query;
    }
]);

However, When I execute this next query, I get a 502 Bad Gateway...

$orders = \App\Order::with([
    'Customer' => function ($query) use ($filterFirst, $filterLast)
    {
        if($filterFirst) {
            $query->where('customers.first', 'LIKE', "{$filterFirst}%");
        }
        if($filterLast) {
            $query->where('customers.last', 'LIKE', "{$filterLast}%");
        }
        return $query;
    },
    'Group' => function ($query) use ($filtercategory)
    {
        if($filtercategory) {
            $query->where('order_groups.groupid', '=', $filtercategory);
        }
        return $query;
    }
]);

Any ideas on how I can further troubleshoot this issue or why it may be happening?



via Chebli Mohamed

How to Protect API routs : Laravel 5.4?

How to make API routes only accessible inside the app?

For example http://ift.tt/2zBpFG3 returns the data as intended but it's really insecure since anyone could access it through postman or the browser.



via Chebli Mohamed

How to use where with Laravel Eloquent Model

I am attempting to

 $orders = \App\Order::with(['Customer'])->where('customers.first', 'LIKE', "{$filterFirst}%");

However, I am getting

 Column not found: 1054 Unknown column 'customers.first' in 'where clause' (SQL: select * from `orders` where `customers`.`first` LIKE %)

How can I use where as well as with?



via Chebli Mohamed

Require Laravel query explanation.

Can anyone explain me what does IF(transactions.retail_cost > 0,1,0) means from the below query ?

       $query = Distributors::selectRaw("distributors.name,distributors.group_id,distributors.pay,SUM(IF(transactions.retail_cost > 0,1,0)) AS trans_number"); 



via Chebli Mohamed

Update row with data from another row in the same table in Laravel

I am trying to update one line with another in my database. I can not find a way to do this.

I have a parent line and a child line. I want to update the PARENT activity with the CHILD activity (draft).

In my controller :

public function update(UpdateRequest $request)
  {
    if (Auth::user()->hasRole('Administrateur'))
    {
        // DRAFT ACTIVITY
        $id = $request->id;
        $activity  = Activity::find($id);

        // PARENT ACTIVITY
        $parent_id = $activity->parent_id;
        $parent_activity = Activity::find($parent_id);

        DB::table('activities')->???

      }
  }

Can you help me ? Thank you very much !



via Chebli Mohamed

BaseController for all controllers

I have many controllers which get CRUD functions. Some of this functions is copy-paste.

I want to create BaseController which has base functions.

But how identify entity?

I have routes:

    Route::group(['namespace' => 'Posts', 'prefix' => 'posts'], function () {
    Route::get('/', 'PostController@index');
});

and function:

public function index()
{
    return Post::filter(Request::input())->paginate()->appends(Request::input());
}

How i can determinate entity Post?



via Chebli Mohamed

why will laravel say all of a sudden Cannot end a section without first starting one in laravel 5.1

@section("page_title", "Home Page")@stop @section("body_class", "page-homepage navigation-fixed-top page-slider")@stop

The above code works just fine for as long as I can remember then yesterday, I ran composer install then aborted in the middle of it.

Afterwards, I started getting the error Cannot end a section without first starting one. I realized the @stop must be removed. I removed it, and everything is fine now, however, I will like to know why @stop suddenly started giving problems.

The version of laravel I was using when @stop started giving problems is Laravel Framework version 5.1.23 (LTS) and the current version which is giving problems with @stop is Laravel Framework version 5.1.46 (LTS)



via Chebli Mohamed

Put to the next column if condition reached in HTML

I'm currently using bootstrap with laravel5.1. What I have now is a list of items and I want to add column and put the other items there if the list of items reached 4 rows. Please see my code below for reference:

@foreach($keys = [1, 2, 3, 4] as $key)
        @if($key == 1)
            <div style="background: #118C8B; padding: 20px 0;">
        @elseif($key == 2)
            <div style="background: #BCA18D; padding: 20px 0;">
        @elseif($key == 3)
            <div style="background: #F2746B; padding: 20px 0;">
        @elseif($key == 4)
            <div style="background: #F14D49; padding: 20px 0;">
        @endif  
            <div class="container">
                <div class="row">
                    <div class="col-md-3 col-sm-3">
                        <img class="center-block" src="" alt="">
                    </div>
                    <div class="col-md-9 col-sm-9">
                       @foreach($items as $item)
                         
                       @endforeach
                    </div>
                 </div> 
            </div>
@endforeach



via Chebli Mohamed

Update a value in a destroy method in Laravel

I make a clone system in Laravel. I want to clone activities.

When I click on "Clone", my line is cloned and receives as the value in the column "parent_id" the ID of the original.

The original gets a value of 1 in the "hasClone" column.

But when I want to delete a clone, in my destroy method, I try to set hasClone (the original entry) to NULL before deleting the clone.

Here is my code :

  public function destroyChanges(Activity $activity)
  {

    $parentActivity = Activity::findOrFail($activity->parent_id)->first();
    $parentActivity->hasClone = NULL;
    $parentActivity->save();

    $activity->delete();

    return redirect()->to('/admin/activity/');
  }

Here is my route :

Route::delete('activity/destroyChanges/{id}', ['as' => 'cancel.activity', 'uses' => 'ActivityCrudController@destroyChanges']);

The entry of the clone is deleted correctly. But he does not update the original entry. How to do ? thank you very much



via Chebli Mohamed

How to solve permission denied error for phantom js in ubuntu?

I am working on a laravel project where I am trying to use php wrapper of phantom js made by jonnyw. I have done everything written in the docs.

I have downloaded the 32 bit executable file and set the path in my code, but it still gives me the following error: sh: 1: /usr/local/bin/: Permission denied

My code looks like this

$client = PhantomJs::getInstance();
$client->getEngine()->setPath('/usr/local/bin/');

I have read some related issues already.

I am using laravel 5.4 and 4.0 version of jonnnnyw/php-phantomjs.



via Chebli Mohamed

mardi 28 novembre 2017

Laravel - Session always expired when redirect to other pages

I having an issues, which is user after login, session will randomly expired when from route to another route.



via Chebli Mohamed

Laravel login, check if username and pwd are a match in my database

In my login form all I need is just username and a password ,trying to use ajax to get data from sqlite .

enter image description here

.AJAX of my login.blade.php

$(document).ready(function(){

  $("#login").click(function(){
    $.ajax({
      type: "GET",
      url: "UserController.php",
      data: { username: $("#username").val(), password: $("#password").val()},
      success: function(data){

        response = JSON.parse(data);
        if(response[0]){

        }
        else{
          alert(response[1]);
        }
      }
    });
  });

});

my User.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class User extends Model
{
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'phone','email', 'password','password_confirmation','librarian'
    ];


}

read method in UserController

//to read data from database to login
    public function read(Request $request){


        $results = DB::select('select * from users where id = :id', ['id' => 1]);

        foreach ($users as $user) {
    echo $user->username;
}

my web.php

Route::get('/login', function () {
    return view('login');
});
Route::get('/signup',function(){
    return view('signup');
});
Route::get('/bookscreate',function(){
return view('bookscreate');
});

Route::get('/','BookController@index');
Route::post('signup', 'UserController@store');
//Route::post('signup', 'UserController@read');

Route::resource('/books','BookController');

So my objective is to go to my database table check username and password if they match one of the DB id then allow user to login .



via Chebli Mohamed

Route management issue Laravel 5.5

This is part of my routes/web.php file

if(Request::is('users/*'))
    {
        require __DIR__.'/users.php';
    }

I have a file named users.php under the same folder

Route::get('profile',[
    'middleware' => 'auth',
    'uses' =>'home\HomeController@profile'])->name('userprofile');

I'm trying to access users/profile route. But it is not working. Please help

Thanks in Advance



via Chebli Mohamed

Can Laravel 5 handle 1000 concurrent users without lagging badly?

I wanted to know that if 1000 users are concurrently using a website built with laravel 5 and also quering database regularly then how does laravel 5 perform ? I know it would be slow but will it be highly slow that it would be unbearable ? Note that i am also going to use ajax a lot.

And lets assume i am using digital ocean cloud service with following configurations

2GB memory
2 vCPU
40GB SSD

I dont expect completely real figures as it is impossible to do so but atleast provide some details whether i should go with laravel with some considerable performance.

Please also provide some some tools through which i can check the speed of my laravel 5 application as well as how it will perform when there is actual load as well as other tools through which i can test speed and performance.

And it would be great if someone has real experience of using laravel especially Laravel 5.

And what about Lumen does that really make application faster than laravel and how much ?



via Chebli Mohamed

How can I solve ErrorExceptionIlluminate\Notifications\SendQueuedNotifications on laravel?

If I executed my notification on production server, there exist error like this :

ErrorExceptionIlluminate\Notifications\SendQueuedNotifications preg_split() expects parameter 2 to be string, array given

I check the error using https://app.bugsnag.com

The full error like this :

enter image description here

On my localhost and my staging server it's no error

It's just error in production server

My notification like this :

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class CheckoutOrder extends Notification implements ShouldQueue, ShouldBroadcast
{
    use Queueable;
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function via($notifiable)
    {
        return ['mail','database','broadcast'];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('test subject')
                    ->view('vendor.notifications.mail.email-checkout-order',['data'=>$this->data, 'name' => $notifiable->name]);
    }
    public function toArray($notifiable)
    {
        return [
            'id'            => $this->data['invoice']->id,
            'time'          => $this->data['invoice']->created_at,
            'group'         => 'purchase',
        ];
    }
}

My env like this :

APP_ENV=production
APP_KEY=secretkey
APP_DEBUG=false
APP_LOG_LEVEL=debug
APP_URL=https://secretapp.co.id

DB_CONNECTION=mysql
DB_HOST=secret
DB_HOST_MONGO=localhost
DB_PORT=3306
DB_DATABASE=secretdb
DB_USERNAME=secretusername
DB_PASSWORD=secretpassword

BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=secret@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

How can I solve this problem?



via Chebli Mohamed

Laravel Custom Validation Method

I'm trying to develop a PHP game with Laravel, and so far a user - with enough gold and not part of a guild - can create a guild using a simple form with one text field. The issue is that currently I'm using Laravel's dd() function in order to show that they failed to have the gold or were already in a guild.

As such, I went looking for a way to give it a more baked-in feel by seeing if I could put this behavior into a custom rule/validator, but I'm unsure as to how to go about this. Examples would be preferred... here's my current function.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|min:4|alpha_dash|unique:guilds'
    ]);

    $char  = Auth::user()->character;
    $cost  = config('game.create-guild-cost');
    $guild = new Guild;

    if($char->gold < $cost) {
        dd('Not enough money');
    }

    if($char->guild != null) {
        dd('You cannot already be in a guild.');
    }

    $guild->name = request('name');
    $guild->leader_id = $char->id;
    $guild->save();

    $char->gold = $char->gold - $cost;
    $char->guild_id = $guild->id;
    $char->save();

    return redirect()->route('guilds.show', ['guild' => $guild]);
}



via Chebli Mohamed

How to use session in custom facade in Laravel 5.5

I am new to Laravel and working on version 5.5. For my knowledge, I have created custom facade and now I am trying to set some session values into this facade as well as try to get the value of set session.

But Laravel is not able to set session in this custom facade. If I do the same thing in controller then it is working fine.

Below are my possible way that I have tried:

public function setUserSession() {  
   //Ist way
   session()->put('user', 'some values');
   var_dump(session()->has('user')); // this is returning me false  

   //2nd way  
   request()->session()->put('user', 'some values');  
   var_dump(request()->session()->has('user')); // this is returning me false 

   Session::set('user', 'some values');  //this is giving me error
   /* for above line I have include below namespace:  
      1.Illuminate\Support\Facades\Session  
   */  
   var_dump(Session::get('user')); // this is returning me false 
}  

Even I have tried the solutions of below link:

How to use session in custom class laravel 5?

But nothing change. Please anyone share your solution for this issue?

Thanks in Advance.



via Chebli Mohamed

Laravel - Passing a Count from a Relationship on a "Simple" Page

I was curious if it was possible to pass along a count of a relationship from a controller and put it on a simple page like a home page (which isn't specifically related to any specific model or controller). So say a user hasMany shipments, how can I pass along the count to the page?

I know how to pass along variables to model specific pages (such as show, edit, index and such pages), but not a general pages such as a home page or about page. I'm sorry if I am a bit oblivious on this topic, but I'm not sure where at all to go about with this.

Thanks! Matt



via Chebli Mohamed

Laravel: Is using download dynamic file a security risk?

I want to offer users in the userarea to download all files from the storage/app/downloads/ folder. I thought about doing it like this in the route file:

Route::get('/home/downloads/{file}', 'Home\DownloadController@show');

and in the controller:

public function show($filename)
{
  $path = storage_path('app/downloads/' . $filename);

  if(!\File::exists($path)){
    return back();
  }

  return response()->download($path);
}

Now I could create a download link for example like this:

<a href="/home/downloads/logo.jpg">Download Logo</a>

I am just not sure if this is a safe way of doing it. Is it possible for users to download files outside the download folder? At least sneaky urls like

/home/downloads/../User.php 

would not be recognizes in route/web.php. But I am not sure if I am overseeing some other possible danger.



via Chebli Mohamed

Laravel Breadcrumbs for Laravel 5.4

I want to install http://ift.tt/1twBDqx on Laravel 5.4.

The link above is for Laravel 5.5. (package version 4.x)

So I go to http://ift.tt/2BvibWb for package version 3.x but I can see that it recommends to install package the same way as it's installed for L 5.5. via:

composer require davejamesmiller/laravel-breadcrumbs

when I run this, I got a mistake: enter image description here

Anybody can help me on how to install it's version 3.x?

Thanks in advance!

UPD: I see the package's author also created a separate for for 3.x version here: http://ift.tt/2BvJUpS but I still don't understand how to install it for Laravel 5.4....



via Chebli Mohamed

Send PUT from pure Javascript to Laravel controller

i try to send data via PUT method, but Laravel 5.5 do not see any data inside Input (or Request) on destination controller.

Here JS:

    function selectProject(option){

        console.log('Update selected');

        var data = new Object();
        data.project_id = option.value;
        data.user_id =;
        console.log(data);

        var url = "/admin/projects";
        var xhr = new XMLHttpRequest();

        xhr.open("PUT", url+'/update_selected', true);
        xhr.setRequestHeader("X-CSRF-TOKEN", "");
        xhr.onload = function () {
                var response = xhr.responseText;
                if (xhr.readyState == 4 && xhr.status == "200") {
                        console.log(response);
                        document.getElementById("app").innerHTML = response; 
                } else {
                        console.log(response);
                        document.getElementById("app").innerHTML = response; 
                }
        }
        xhr.send(data);
    }

inside Laravel controller i try to showing inputs:

    echo '[Controller]Inputs:';
    return Input::all();

Here output from console.log:

Update selected
{…}
 project_id: "4"
 user_id: 1
 __proto__: Object { … }
[Controller]Inputs:[]

Question: what i'am doing wrong and where is inputs data? p.s. I can use only pure javascript, no jQuery or anothers.



via Chebli Mohamed

Laravel blade + vue render ajax data couple?

i want to write ajax rendering news using blade + vue.

<div id="news">
    <div class="l_news">
        <div class="post" v-for="post in posts">
            <div class="image" style="background: url() no-repeat center / cover">
                <div class="title">@</div>
            </div>
            <div class="desc">@</div>
        </div>
    </div>
</div>

I have some problem with rendering post image.

But i can't use

url(') }})

How to write correctly?

Thanks in advance!



via Chebli Mohamed

laravel config file retun null in config folder

I have a config file called fcm.php in config folder in laravel. The file looks like this:

<?php
return [
    'driver' => env('FCM_PROTOCOL', 'http'),
    'log_enabled' => true,

    'http' => [
        'server_key' => config('app.fcm_mode') == 'user' ? env('FCM_SERVER_KEY', 'Your FCM server key') : env('FCM_DELIVERY_SERVER_KEY', 'Your FCM server key'),
        'sender_id' => config('app.fcm_mode') == 'user' ? env('FCM_SENDER_ID', 'Your sender id') : env('FCM_DELIVERY_SENDER_ID', 'Your sender id'),
        'server_send_url' => 'http://ift.tt/1TmHkUo',
        'server_group_url' => 'http://ift.tt/1mkLeNy',
        'timeout' => 30.0, // in second
    ],
];

It works properly in my localhost(I vendor:publish fcm.php config file), But in a shared host, config('app') return null in this file(config/fcm.php)

What is the problem? Thanks



via Chebli Mohamed

Filter data in form request in Laravel 5.5

I have generated new form Request for the controller, but I do not know how to filter data before there will handle in the validator and so on.

Are there some native solutions in Laravel for this case?

class TestRequest extends FormRequest
{

  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize()
  {
      return true;
  }

  /**
   * Get the validation rules that apply to the request.
   *
   * @return array
   */
  public function rules()
  { 


    return [
       "title" => "required|string",
       "order" => "required|integer"
    ];
  }

}

class TestController extends Controller
{ 
     public function store(TestRequest $request, $chapterId)
     {
       // some business logic
     }
}

There is some solution in Laravel 5.5 but in this example author uses validate for filtering data from request, but I need to use filter inside TestRequest

 $data = $this->validate(request(), [
         //...
    ]); // I can't use this inside TestRequest



via Chebli Mohamed

Try upload videofile

I use Laravel 5.4 and I try upload video file. Image file upload successfully.

$video = Request::file('video_file')) {
        $fullName = 'videos/'.uniqid().time().'.'.$video->getClientOriginalExtension();
        Storage::disk()->put($fullName, $video);

But it didn't work. When I try get information about file - size = 0

What I do wrong?



via Chebli Mohamed

Method not allowed in Laravel. Why in this case?

I would like to know why I have a "Not Allowed" method in this case. I'm trying to set a value to NULL (I have an hasClone column) when I delete an entry that I duplicated.

My controller :

public function destroyChanges($id)
  {
    $activity = Activity::findOrFail($id);
    $activity->delete();

    return redirect()->to('/admin/activity/setCloneNull/' . $activity->parent_id);
  }

public function setCloneNull($id, Activity $activity)
{
  $activity = $activity->where('id', '=', $id)->first();
  $activity->hasClone = NULL;
  $activity->save();
  return redirect(url('/admin/activity/'));
}

Routes :

  Route::delete('activity/destroyChanges/{id}', ['as' => 'cancel.activity', 'uses' => 'ActivityCrudController@destroyChanges']);
  Route::post('activity/setCloneNull/{id}', ['as' => 'setCloneNull.activity', 'uses' => 'ActivityCrudController@setCloneNull']);

How to make it work? thank you !



via Chebli Mohamed

Why send email use mail laravel does not work if it use shouldqueue?

My mail laravel like this :

<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;
    public $order;
    public $store;
    public function __construct($order, $store)
    {
        $this->order = $order;
        $this->store = $store;
        $this->subject('subject');
    }
    public function build()
    {
        $company_email = explode(',',config('app.mail_company'));
        return $this->view('vendor.notifications.mail.email-order-received',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($company_email);
    }
}

My env like this :

BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
SESSION_DRIVER=file
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

If the code executed, it does not works. The email failed sended or the mail code not executed

But if I remove implements ShouldQueue, it works. The email success sended

Why if I use shouldqueue it does not works?



via Chebli Mohamed

Laravel How to skip elements if query is null in foreach loops?

I want to show latest posts in each category. If all category is not null, its OK, But if there are empty categories Trying to get property of non-object error. (I mean if category dosen't have any post)

So how can I pass thos categories post, when query returns null ?

Controller;

$categories=Category::with('posts')->latest()->get();
return view('frontend.home',compact('categories');

Blade;

@foreach($categories as $category)

<div class="col-md-3">
  <div class="card text-white">
    <a href="#"> <img class="card-img"
       src=""  alt="Card image">                                             

      <div class="card-img-overlay">
      <h4 class="card-title"></h4>
      </div>
    </a>
  </div>
</div>

@endforeach

Any advice ?



via Chebli Mohamed

Laravel AJAX/API request not working on AWS

My Laravel 5.5 app has a very simply AJAX POST to the server that works perfectly locally, but returns a 500 Server Error when deployed to my Elastic Beanstalk instance.

I've narrowed down the issue somewhat, but I'm still stumped.

I'm using a route defined in routes/api.php:

Route::post('availabletimes','TimesController@show');

As I test I have reduced TimesController@show to be simply:

public function show(GetShowTimes $request) {
  return "OK";
}

It couldn't be simpler.

I've checked that the X-CSRF-TOKEN is being sent. I've used Postman to test this, as well as my site, and the result is the same: Locally works fine (returns "OK"), deployed to AWS just returns a 500 Server Error.

I've looked through the server logs, and I can see the error being raised, but there's no other information:

"POST /api/availabletimes HTTP/1.1" 500

How can I debug this?



via Chebli Mohamed

Laravel return object with nesting

Assume the following models:

class Character extends Model
{
    protected $fillable = ['items'];
    protected $guarded = ['id'];

    public function items(){
        return $this->hasMany("App\Item");
    }
}

class Item extends Model
{

    public function character(){
        return $this->belongsTo("App\Character");
    }

}

When a request is made, the controller performs the following:

public function getCharacter(Request $request, $characterID = 0){

        $characters = array(Character::find($characterID));

        foreach($characters as $key => $value){
            //ADD THE ITEMS
            $characters[$key]->items = $characters[$key]->items;
        }
        return $characters;
    }

------This works fine.
Im getting a character json with a member "items" that holds all the data for the corresponding item models.

However, assume Items didnt belong to Character but to ItemPackage. Specifically, Items belong to ItemPackage ( ItemPackage has many Items ) and ItemPackage belongs to Character ( Character has many ItemPackage(s) )

In a similar fashion, i tried performing the following in the controller but it doesnt work.

....
foreach($characters as $key => $value){
    //ADD THE ITEM
    $characters[$key]->itemPackages = $characters[$key]->itemPackages
    //the above line works but we also need to add the item obj data so:
        foreach($characters[$key]->itemPackages as $key2){
            $characters[$key]->itemPackages[$key]->arrayOfItems = "whatever here";
        }
    }
....

Specifically, i get an error of : Undefined offset: 1. Im clearly not understanding the data structures im operating on very well, maybe someone could illuminate me.

Thanks for taking the time



via Chebli Mohamed

CRUD -> Destroy Method

I'm not sure how to make a destroy method yet. Can you guys give me a hand here?

I'm using this form:

@foreach($data as $d)
<tr>
<td> </td>
<form method="POST" action="/newuser/delete/{$d->id}">
<input type="hidden" _method="DELETE">   
<td><button type="submit" class="btn btn-default btn-sm">Excluir</button></i></a></td>
</form>
</tr>

@endforeach 

This Controller:

    public function search(Request $request)
    {
    $users = Users::search($request);
    $users1 = Groups::search($request);
    foreach ($users as $user) {
    $data[] = array('Username' => $user->username,
    'id' => $user->id
    );
    };
    foreach ($users1 as $user1){
    $data1[] = array ('id2' => $user1->id);
    };
    return view('user.buscar', compact('data'));
    }

    public function buscar()
    {
    return view ('user.buscar');
    }

    public function destroy($id)
    {
    try {
    DB::transaction(function() use($id)
    {
    $user = Users::find($id);
    $user1 = Groups::find($id);
    $user->delete();
    $user1->delete();
    });
    return redirect('home')
    ->with('message', 'Usuário removido com sucesso!!');
    }
    catch (\Exception $e) {
    return redirect('home')
    ->with('message', 'Usuário não foi removido, verifique os dados!!');
    }

And using this route Route::delete('newuser/delete/{$d->id}', 'UserController@destroy');

I not sure if what I'm doing is right. Please, Be patient I'm new to this.



via Chebli Mohamed

Laravel 5.5 not found class with correct namespace

My ./app folder looks like:

+-- app
   +-- Classes
       +-- Events
          +-- EventBase.php
          +-- EventX.php

There's nothing secret with EventX file:

<?

namespace App\Classes\Events;

class EventX {
  // ...
}

EventBase.php represents a Facade that inside it I just try to instantiate an EventX:

public function someMethod() {
  new \App\Classes\Events\EventX;
  // ...
}

After this line, Framework throw an exception telling that class was not found:

Symfony\Component\Debug\Exception\FatalThrowableError (E_ERROR)
Class 'App\Classes\Events\EventX' not found

I already had this issue before when trying to create Facades and solved by moving class file from his current directory and after moving back (yeah, I don't why but it worked).

Something tells me that this is an issue of autoload process, so I tried these command (but still not working):

php artisan cache:clear

php artisan clear-compiled

php artisan config:clear

composer dump-autoload

What can I do in order to investigate the problem?



via Chebli Mohamed

Supervisor stops/terminates before timeout

I know this might be a hard question as it concerns supervisord queueing but I hope someone would be able to try and think with me to solve an application-breaking problem.

The scenario I'm in at the moment is that I have an application that runs huge imports, each on its own supervisor thread/proc and even though the timeout of the queue is set to either 0 or 3600, the supervisor queue keeps terminating before the 3600 mark, generally after about 30-40 minutes.

I've tracked the RAM- & CPU-usage for an import but this could not be the problem as I am using max. 2GB / 8GB ram and the CPU is using only 1 thread with around 20% usage.

My supervisor queue looks as follows:

[program:laravel_queue]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/application/artisan queue:work --sleep=3 --tries=1 --queue=application --timeout=0
autostart=true
autorestart=true
user=administrator
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/application/storage/logs/queue/laravel_queue.out.log
stderr_logfile=/var/www/application/storage/logs/queue/laravel_queue.err.log

I've tried the same variant with --timeout=3600, but the queue still terminates at about 40 minutes.

I'm running the same setup in a Homestead/Laravel VM, and it runs perfectly in the Homestead VM.

Am I missing some redis configuration setting that terminates connections after 40 minutes? I'm running a cluster-system where there is 1 seperate - remote - redis-server which the application(s) talk to.

I want to provide more information but I'm not sure what more I could provide that would be helpful, so if you have any thoughts, I'm probably willing to provide most information.

Thanks in advance.



via Chebli Mohamed

Laravel query building with join and groupBy

I tried building this query with Laravel

$products = DB::table('products as p')
            ->join('manufacturers', 'manufacturers.id', '=', 'p.productManufacturerID')
            ->join(DB::raw('SELECT  *
                 FROM `product_options`
                 GROUP BY productID'),function($join){
                        $join->on('product_options.productID', '=', 'p.id');
            })
            ->select('p.productSKU', 'p.productName','p.productPrice',
                'p.productSize','p.productDescription','p.productQuantity',
                'manufacturers.brandName')
            ->where('p.productCategoryID', $category->id)
            ->get()->toArray();

and getting error http://ift.tt/2ibBAXq what is the issue there



via Chebli Mohamed

multiple middleware to Laravel 5 route not working

i want to view dashboard when logged in as both "admin" and "jeweller". When i log in a "admin" its redirecting to dashboard, when when i log in as jeweller, its not going to dashboard. I have 2 types of admin & tables ie.. "admin", "jeweller"

In auth.php , i have created 2 types of providers

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'jeweler' => [
            'driver' => 'session',
            'provider' => 'jewelers',
        ],
    ],
 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
        'jewelers' => [
            'driver' => 'eloquent',
            'model' => App\Jeweler::class,
        ],
    ],

i have declared a middleware called "AdminAuthenticated" , in AdminAuthenticated.php we have

class AdminAuthenticated
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return $next($request);
        }
        return redirect()->route('admin.login');
    }
}

and in web.php we have

Route::group(['prefix' => 'admin','middleware'=>
  ['adminAuth:admin','adminAuth:jeweler']], function () {
});

and in kernal we have

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'adminAuth' => \App\Http\Middleware\AdminAuthenticated::class,
    ];



via Chebli Mohamed

Undefined variable: task (View: C:\Users\13\Desktop\TDT\resources\views\files\form.blade.php) in Laravel

i need print task_id in file table when some user is going to attach files. this is My form.blade.php file action

files/form.blade.php

action=""> //and this is line 39

and this is FilesController

 private function saveUploads(Request $request, $fileUrl, $id,$taskId)
    {
        $file = new File;
        $file->file_name  = $request->file('file_name')->getClientOriginalName();
        $file->file_url   = $fileUrl;
        $file->project_id = $id;
        $file->task_id = $taskId;


        $file->save();
    }

and this is My file attachment routes

Route::post('projects/{projects}/files', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);

and My file/form.blade.php is include with show.blade.php file in task folder in view directory

tasks/show.blade.php


<hr>
{!!$task->body!!}
<hr>
@include('comments.form')
@include('files.form') // form.blade.php include

but unfortunately I got this following errors

ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 39:
Undefined variable: task (View: C:\Users\13\Desktop\ddd\resources\views\files\form.blade.php)

how can fix this problem?



via Chebli Mohamed

laravel eloquent merge 2 queries before executing them?

I have 2 queries like this:

$expiresAt = Carbon::now()->addMinutes(10);
$thumbnails = Cache::remember('entities-thumbnails-'.$entity_id, $expiresAt, function () use ($entity_id) {
    return Images::where(['entity_id' => $entity_id, 'image_style' => 'thumbnail'])
        ->select('path AS thumbnail', 'width As thumbnailWidth', 'height As thumbnailHeight');
});
$largeImages = Cache::remember('entities-largeImages-'.$entity_id, $expiresAt, function () use ($entity_id) {
    return Images::where(['entity_id' => $entity_id, 'image_style' => 'large'])
        ->select('path AS src')
        ->union($thumbnails)
        ->get();
});

What I want to do is not execute them seperately but as one query. Overall there will be 4 queries therefore instead of doing 4 I want to do one, is that possible? How does union work exactly?



via Chebli Mohamed

Show first 50 words

I have a long paragraph as a description, in the summary, I want to show just part of that, the first 50 words. This description stored in the database.

So how can I show just the first 50 words of this description? I am using Laravel 5.5.

I call it like that:



via Chebli Mohamed

lundi 27 novembre 2017

Why mail laravel not working on the staging server?

I try on the my localhost, it works

But if I try on the staging server, it does not works

My controller like this :

<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderReceivedMail;
...
class PurchaseController
{
    ...
    public function test() {
        $order = $this->order_repository->find(416);
        $user = $this->user_repository->find(1);
        Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
    }
}

My mail like this :

<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;
    public $order;
    public $store;
    public function __construct($order, $store)
    {
        $this->order = $order;
        $this->store = $store;
        $this->subject('subject');
    }
    public function build()
    {
        $mail_company = explode(',',config('app.mail_company'));
        // dd($mail_company, $this->order->number, $this->store->name, 'test');
        return $this->view('vendor.notifications.mail.email-order',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($mail_company);
    }
}

I try add this :

dd($mail_company, $this->order->number, $this->store->name, 'test');

on the mail

If in my localhost, the result of dd show

But if in the staging server, the result of dd not show

Seems if the staging server, it does not run this statement :

Mail::to($user)->send(new OrderReceivedMail($order, $order->store));

How can I solve this problem?



via Chebli Mohamed