Always load the relationship data with eager loading in Laravel

Created 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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.