Laravel Relationship with Count on hasMany Relation

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Dev’s, Now In this example,I will teach you how to laravel relation with count. Here we can simply use to laravel hasmany with count in our application. Here we know Laravel Relationship with Count on hasMany Relation.

So we can get total record in relationship through then we use also withCount function. In this function we will get total number of record with relationship.

So If we want to count the number of results from a relationship and also without actually loading them we may use the “withCount” method.

Example 1 :

public function index(Request $request)
{
	$states = state::get();
	return view('welcome',compact('states'));
}

===================

@foreach($states as $key => $value)

    echo $value->stateuser->count()   

@endforeach

Example 2 :

public function index(Request $request)
{
	$states = state::withCount('stateuser')->get();
	return view('welcome',compact('states'));
}

===================

@foreach($states as $key => $value)
{
    echo $value->stateuser_count    
}
@endforeach

Read Also: How to check current date between two dates in PHP ?

Thanks for read. I hope it help you. For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →