
Use withCount() to get total number of records with relationship
-
Get number of records with relationships in Laravel Eloquent using withCount() method
//app\Http\Controllers\<YourController>.php public function index() { $posts = Post::withCount(['comments'])->get(); return view('posts', compact('posts')); } //resources\view\posts.blade.php <table> @foreach ($posts as $post) <tr> <td>Post <b> {{ $post->title }} </b> has <b> {{ $post->comments_count }} </b> comments </td> </tr> @endforeach </table> //app\Models\Post.php public function comments() { return $this->hasMany('App\Models\Comment'); }
0You can get the relationship records count without loading data using withCount() method. You have to first define the comments method with hasMany relationship in your post model. If you don’t know how to create hasMany relation you can find it here laravel hasMany method. After that you can call withCount() method on comments method which returns you the number of comments associated with this particular post without actually loading them (data from relationship table).
This code snippet has been tested and it's working in laravel 8. First you have to define a route in web file, create a hasMany relationship method (comments) in post model, create a method in controller file and return data to view and after that dispaly data in view file.
Post Quibusdam ipsam est nihil explicabo. has 3 comments
Post Inventore cupiditate dolores officiis enim accusantium. has 4 comments
Post Ea delectus et incidunt. has 1 comments
Post Excepturi ducimus quo sapiente nesciunt amet. has 1 comments
Post Asperiores maxime maiores sed. has 1 comments
Random Code Snippet Queries: Laravel
- How to restore multiple records after soft-deletes in Laravel
- Trying to get property 'title' of non-object
- Laravel onclick function not working
- Get ids in array from users table
- Insert data with form validation using ajax in laravel
- How to get all posts which contains comments in laravel
- How to avoid duplicate entries in pivot table in Laravel
- How to create new user without form submission in laravel
- How to display 1 day ago in comments in laravel view
- Symlink(): No such file or directory
- Remove array keys and values if it does not exist in other array in Laravel
- How to call model in blade laravel
- How to check data inserted or deleted in pivot after toggle method
- Insert values in pivot table dynamically in laravel
- Get latest record by created at in Laravel
- Get id of last inserted record in laravel
- How to get file extension from input type file in laravel
- Create model with migration and seeder
- Laravel create multiple records in Pivot table
- Attempt to read property "avatar" on null in Laravel
- How to pass query string with pagination in laravel
- Rendering HTML from database table to view in Laravel
- How to get column names from table in Laravel
- How to Get records between two dates in Laravel
- 419 page expired error in Laravel