Always load the relationship data with eager loading in Laravel

You can always load the relationship data with eager loading in Laravel. You have to define the magic property $with in model with relationship method name.

Answers 1
  • Always load relationship data (posts) to user using eager loading

    //app\Models\User.php
    <?php
    
    namespace App\Models;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Support\Facades\Event;
    
    class User extends Authenticatable
    {
        
        use HasFactory, Notifiable;
    
        protected $with = ['posts'];
    
        public function posts(){
            return $this->hasMany('App\Models\Post');
        }
    
    }
    
    //routes\web.php
    Route::get('/user-with-posts', function(){ 
        $userWithPosts = App\Models\User::find(1);
        dd($userWithPosts); 
    });
    
    1

    You have to define the magic propety $with in user model. It will always display the posts associated with the user. Your query will always load the post data with the user. 

  • Back to code snippet queries related laravel