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 get laravel errors folder in views directory in laravel
- How to get data from two tables in laravel
- Comment .env file in laravel
- How to check find method executed successfully in laravel
- How to update record after save method in Laravel
- Redirect from www to non www in laravel using htaccess
- How to prevent host header attack in Laravel
- Laravel append URI in route
- Delete all related comments on deleting a post in Laravel
- How to disable timestamps in laravel
- How to display 1 day ago in comments in laravel view
- SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
- How to make Copy or Duplicate table row in laravel
- How to change default timestamp fields name in Laravel
- How to call Laravel route in jQuery
- Rendering HTML from database table to view in Laravel
- How to add unique records in pivot columns of Laravel pivot table
- SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'posts_user_id_foreign'; check that column/key exists
- Laravel migration add foreign key to existing table
- How to restore multiple records after soft-deletes in Laravel
- How to check data inserted or deleted in pivot after toggle method
- Permission denied error while creating storage link in Laravel
- Link storage folder in laravel 8
- Laravel change date format
- Display success message in laravel