Laravel Relationship with Count on hasMany Relation

10-Apr-2023

.

Admin

hi Guys,

In this example,I will learn you laravel relation with count.you can simply use to laravel hasmany with count.

You can get total record in raltionship through then use withCount function.In this function you get total number of record with relationship.

If you want to count the number of results from a relationship without actually loading them you 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

It will help you.....

#Laravel

#Laravel 6