Always load the relationship data with eager loading in Laravel

Updated at 17-Nov-2021, By samar

Always load the relationship data with eager loading in Laravel

Through the use of the programming language, we will work together to solve the "Always load the relationship data with eager loading in Laravel" puzzle in this lesson.

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.
  • 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); 
    });
    

    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