How to check records exist in loaded relationship in Laravel blade view
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.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: Laravel
- How to display order by null last in laravel
- How to use more than one query scope in Laravel
- Return view from route Laravel
- Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0"
- The use statement with non-compound name 'Auth' has no effect
- Get the products list ordered by a user
- How to get count of all records created at yesterday
- Laravel 10 Breeze Authentication Example
- Laravel route parameter
- How to use or operator in laravel
- Create model with migration and seeder
- How to increment column value of table in Laravel
- Rename Pivot Table in Laravel
- Ajax POST request in laravel
- InRandomOrder() method with example in laravel
- How to get last month records in Laravel
- Laravel create default admin user
- If condition in Laravel 9
- How to get id of next record in laravel
- Page loader in laravel
- Get current URL on visit URL in Laravel
- Cast Array to an Object in Controller and then pass to view in laravel
- Target class [HomeController] does not exist
- Remove array keys and values if it does not exist in other array in Laravel
- Class 'App\Rules\Hash' not found in Laravel