How to check records exist in loaded relationship in Laravel blade view

Created at 15-Nov-2021 , By samar

How to check records exist in loaded relationship in Laravel blade view

With this article, we will examine several different instances of how to solve the "How to check records exist in loaded relationship in Laravel blade view".

You can check record exist or not in loaded relationship in Laravel blade view. Sometimes we have to check that the records exists or not in nested relationship, in that case it helps you to find out the solution for you
  • Check records exist in loaded relationship in Laravel blade view

    //routes\web.php
    Route::get('/user-with-posts', function(){
        $userPosts = App\Models\User::withCount('posts')->find(1);
        return view('home', compact('userPosts'));
    });
    
    //resources\views\home.blade.php
    @if($userPosts->posts_count > 0 )
        <p> data exists in relationship! </p>
        @foreach($userPosts->posts as $post)
                <h5> {{ $post->title }} </h5>
        @endforeach
    @else
        <p> data is not exist in relationship! </p>
    @endif
    
    //app\Models\User.php
    public function posts(){
        return $this->hasMany('App\Models\Post');
    }
    

    You have to create the posts table with foreign key (user_id) column and the posts relationship method in user model.

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.