Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

screwtape_mk's avatar

Trying to get property of non-object

Hi Guys

I have the following variable:

    $bookings=Auth::User()->bookings;

and i get the error:

ErrorException Trying to get property of non-object

I have the following Models:

User:

    public function bookings() {
        
            return $this->hasMany('App\Models\Bookings');
    
    }   

Bookings:

<?php namespace App\Models;


use Illuminate\Database\Eloquent\Model;



class Bookings extends Model 
{


    
    protected $table = 'V_BOOKINGS';
    


    public function User(){
    
        return $this->belongsTo('App\Models\User');
    
    }
    
    

    
    
    public $timestamps = false;


}

Route:

Route::get('/bookings',[
            'uses'=>'\App\Http\Controllers\AuthController@getBookings',
            'middleware'=>['guest'],

]);

Please assist i might have missed something

0 likes
3 replies
tykus's avatar

Auth::user() is null - you have explicitly set the guest middleware on this route, so that should not be unexpected. Change the guest middleware to auth, and you should be good - presuming that makes sense in the context of your app.

Be careful about your cases, a case-sensitive OS will not like Auth::User() as the method is Auth::user()

1 like
screwtape_mk's avatar

Thanks alot guys my problem is solved- i am not sure if the Case sensitive issue might have solved my problem. What i instead decided to do is to create a separate controller to handle '''bookings''' instead defining a method inside the AuthController. This way i had a better view of which models were used where. Thanks so much though

Please or to participate in this conversation.