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']; } 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 i guess that did the trick
