Yearly Archives: 2017


Methods to obtain Laravel 5.5 user ID

Obtaining the user instance in Laravel Controller;

All these return the same result

dump($request->user()->id);        //using the $request variable passed into to controller

dump(request()->user()->id);        //using the request() helper method

dump(Auth::id());                   //using Auth facade

dump(Auth::user()->id);             //getting user object from Auth facade

dump(auth()->id());                 //using auth() helper

dump(auth()->user()->id);           //getting user object from auth helper

Methods that use the id from the user object will throw an error if there is no logged in user


Using multiple Laravel pagination links on one page

I came across a problem in a Laravel 5.3 project where I wanted two independent paginated areas on a single view.

multiple-pagination

Using just {{ $model->links() }} on the page would cause both lists to be paged at the same time since the URL contains ?page=1 and does not distinguish which set is being paged.

The answer is to include additional parameters to the paginate() function in the controller.

https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_paginate

By passing in a third parameter we can change the default ‘page’ to a name that can vary for our two sets of data.

 

    public function index()
    {
        $cbShows = Show::champBreed()->paginate(150, ['*'], 'cbShows');
        $owShows = Show::openWorking()->paginate(300, ['*'], 'owShows');

        return view('shows.index')->with(compact('owShows','cbShows'));
    }

We can now page through the two sets of data independently. The links will be adapted like

/shows?owShows=3

The second parameter [‘*’] is an array of the columns to be selected and must be set in order to allow the third parameter to be passed.