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

Updated 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