How to check relationship is loaded or not in Laravel

Updated at 15-Nov-2021, By samar

How to check relationship is loaded or not in Laravel

Good day, guys. In this post, we’ll look at how to solve the "How to check relationship is loaded or not in Laravel" programming puzzle.

You can check relationship is loaded or not in Laravel. Sometimes you have to find out the relationship method is loaded or not on model in that case it helps you to find out the solution for you.
  • Check relationship is loaded or not on model in Laravel

    //routes\web.php 
    Route::get('/user-with-posts', function(){ 
        $userPosts = App\Models\User::with('posts')->find(1); 
        return view('home', compact('userPosts')); 
    });
    
    //resources\views\home.blade.php
    @if($userPosts->relationLoaded('posts'))
        <p> Relationship loaded! </p>
    @else
        <p> Relationship not loaded! </p>
    @endif
    

    This method checks that the relationship is loaded to model or not.

    app\Models\User.php

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

Back to code snippet queries related laravel