How to check relationship is loaded or not in Laravel

Created 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

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.