Ad

Laravel 5.1 - Can't Access Auth:user()->data From My Controllers

I've been having a little trouble with Auth data in Laravel 5.1 I want to get the id of the Logged user and It works if I use it in a View, lets say:

<?php echo Auth::user()->id;?>

But if I try to access to it in a Controller it dowsnt work, and I get this error:

ErrorException in Con_Mascota.php line 101:
Trying to get property of non-object

In line 101 i've:

$cod_usu=$request->user()->cod_usu;

I changed that from $cod_usu=Auth::user()->cod_usu; cause that didnt work either.

Im also including it in the Controller:

use Auth;

Any help is much appreciated :)

I believe the problem is my Auth session is login out after refresh or after i go to another route:

My login funcions is:

    */
public function ini_ses(Request $datos)
{
    //Inicia sesion
  //  Session::put('ses_correo', Input::get('email'));

    $correo = $datos->input('email');
    $password= $datos->input('password');        

    if(Auth::attempt(['correo_elec'=>$correo, 'password'=>$password]))
    {
        $_session['correo']=$correo;
        $_session['contra']=$password;

        if(Auth::user()->tipo==0)
        {
            return view('cliente');
        }
        elseif(Auth::user()->tipo==1)
        {
            return view('veterinario');
        }
        elseif(Auth::user()->tipo==2)
        {
            echo("Admin");
        }
    }
    else
    {
        var_dump($correo, $password);
    }
}

Model:

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class Usuario extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    public $timestamps = false;
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'usuario';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['cod_usu', 'correo_elec', 'nombre', 'ape_p', 'ape_m', 'telefono', 'celular', 'pais' , 'tipo'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['contra', 'remember_token'];
}

enter image description here

I found the solution, i changed this:

if(Auth::attempt(['correo_elec'=>$correo, 'password'=>$password]))

to this

if(Auth::attempt(['correo_elec'=>$correo, 'password'=>$password], true))

that eventyally made me have to change my cod_usu in the table for id, and reading jedrzej.kurylo's answer made me have to change my cod_usu in the table for id, and reading jedrzej.kurylo's answer i guess that did the trick

Ad

Answer

When you log in, Laravel tries to save your user identifier in the session so that it can load it during subsequent requests. By default, model's ID field is called id, which is not true in your case. Therefore, after you authenticate, Laravel stores null as your user's ID and that's the reason it cannot load it later.

You need to tell Eloquent what is the name of your identifier column. You can do it by setting $primaryKey property of your Usuario class:

protected $primaryKey = 'cod_usu';

You'll need it not only to make your login work, but also to be able to define relations or make find method work for your models , e.g. Usuario::find(123) won't be able to load your user from the database.

Enabling remember-me, that helped in your case, worked by accident. By setting second parameter of attempt() to true you've enabled remember-me feature which results in creating a random identifier that is saved in remember_toke column in your table and later used to load your user data. It's not a proper way of handling your issue, it also will break your application if you decide to disable remember-me in the future.

Ad
source: stackoverflow.com
Ad