Error trying to access Auth::user()->id, in Laravel 5.8

Asked

Viewed 104 times

-1

Error:

Auth::user()->id trying to get a property of a non-object

Model:

<?php

namespace App\Models;

use App\Scopes\Tenant\TenantScope;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Devedor extends Model
{
    protected $fillable = [

        'nome',
        'endereco',
        'logradouro',
        'numero',
     //code

    ];
    public static function boot()
    {
        parent::boot();

        //$user = User::isAdmin();

        $usuario = User::findOrfail(Auth::user()->id); //Erro aqui

        $usuario->existePapel('Admin');

        if ($user) {
            echo "Usuario encontrado";
        }
        static::addGlobalScope(new TenantScope);
    }


}
  • Auth::user() there’s something here, and another question, you’re logged in?

  • Yes, I’m logged in, but it’s not working inside the model

  • I think it’s weird, but, um, var_dump(Auth::user()) and check what returns, what you did if you are logged in works ...

  • Thanks Virgilio, but I’ve already solved with Guilherme’s tip

  • You solved apparently ... but, broke the code, because if this is not working when the user is theoretically logged in (Auth::user()->id) your code has problems.

  • Another thing, if you’re doing it in the wrong place, you should have ( middleware) to verify this, being that this is done in the routes

  • Yes, I am using Middleware and that’s the weirdest thing about it not working Auth::user()->id

  • look I don’t know what you’re doing, but if it doesn’t work with the login successfully ta wrong and something else there is in the model shouldn’t be there ... well are only alerts

  • I’ll find out for sure. Thank you Virgilio

Show 4 more comments

1 answer

1


Probably running "deliberately" without checking if the user is logged in, just use Auth::check():

use Illuminate\Support\Facades\Auth;

...


if (Auth::check()) {
    ... Aqui vai o seu código ...
}

To get the id as the documentation would be:

$id = Auth::id();

Documentation: https://laravel.com/docs/5.8/authentication

  • Thanks man, that’s right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.