Asked  7 Months ago    Answers:  5   Viewed   39 times

I'm using Laravel 5.3 and I'm trying to get the authenticated user's id in the constructor method so I can filter the user by assigned company as follows:

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateSupportFacadesView;
use AppModelsUser;
use AppModelsCompany;
use IlluminateSupportFacadesAuth;


class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests ;

    public $user;
    public $company;


    public function __construct()
    {


        $companies = Company::pluck('name', 'id');
        $companies->prepend('Please select');
        view()->share('companies', $companies);
        $this->user = User::with('profile')->where('id', Auth::id())->first();
        if(isset($this->user->company_id)){
            $this->company = Company::find($this->user->company_id);
            if (!isset($this->company)) {
                $this->company = new Company();
            }
            view()->share('company', $this->company);
            view()->share('user', $this->user);
        }

    }

However this doesn't return the user id. I've even tried Auth::check() and it doesn't work.

If I move the Auth::check() out of the __construct() method then this works as follows:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        dd(Auth::check());
        return view('home');
    }
}

However this fails if I put this in the construct method in the HomeController too!

Any ideas why this is failing?

 Answers

37

docs

you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

class ProjectController extends Controller
{
    /**
     * All of the current user's projects.
     */
    protected $projects;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->projects = Auth::user()->projects;

            return $next($request);
        });
    }
}
Wednesday, March 31, 2021
 
dzm
answered 7 Months ago
dzm
59

Check your credentials first if they are correct, Secondly check your model table which uses LaravelPassportHasApiTokens trait that whether it contains email column, because by default it is used to identify user when validating credentials. if your table has username column or any other column which is used in validating credentials you must define a function findForPassport in that model. like this,

public function findForPassport($username) {
       return self::where('username', $username)->first(); // change column name whatever you use in credentials
    }

I use username and password column to validate a user, in {project_directory}vendorlaravelpassportsrcBridgeUserRepository.php

this function validates your credentials,

public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity)
    {
        if (is_null($model = config('auth.providers.users.model'))) {
            throw new RuntimeException('Unable to determine user model from configuration.');
        }

        if (method_exists($model, 'findForPassport')) { // if you define the method in that model it will grab it from there other wise use email as key 
            $user = (new $model)->findForPassport($username);
        } else {
            $user = (new $model)->where('email', $username)->first();
        }

        if (! $user || ! $this->hasher->check($password, $user->password)) {
            return;
        }

        return new User($user->getAuthIdentifier());
    }

notice the second if statement and you will get to know what is happening there.

hope this help :)

Wednesday, March 31, 2021
 
Sethunath
answered 7 Months ago
30

Check the primary key of your users database. If you set your table's primary key other than id, you need to set it in your User model.

The Laravel Documentation states the following:

Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

For example, if you have a user_id column set as your primary key in your users database, you need to place the code below in the User model:

protected $primaryKey = 'user_id';

Wednesday, March 31, 2021
 
Classified
answered 7 Months ago
68

It changed in 5.2 version.

If you will use session, csrf, cookie ext. you should to use "web" middleware like this in your routes:

Route::group(['middleware' => ['web']], function () {
//
});

And you can see in your project the new kernel.php file is like this:

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        AppHttpMiddlewareEncryptCookies::class,
        IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
        IlluminateSessionMiddlewareStartSession::class,
        IlluminateViewMiddlewareShareErrorsFromSession::class,
        AppHttpMiddlewareVerifyCsrfToken::class,
],

'api' => [
    'throttle:60,1',
],
];

More info: https://laravel.com/docs/5.2/releases

Saturday, May 29, 2021
 
Gilko
answered 5 Months ago
78

Login function needs user of type Authenticatable and you just given email which is string thats why you get this error, Either use Auth::loginUsingId($id);

 $user = User::where('email','=',$email)->first();
 Auth::loginUsingId($user->id, TRUE);

Or just

Auth::login($user);
Friday, August 13, 2021
 
lechup
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :