PHP, Laravel, Javaascript tips and tricks and Tech in general
// basic usage of whereHas()
$user = App\Models\User::where('name', 'john')->first();
$post = App\Models\Post::whereHas('user', function($query) user($user){
$query->where('id', $user->id);
})->get();
Read more
The tap
method on a collection allows to "tap" into a collection at a specific point and do something with the result while not affectiong the main/original collection.
Here is an example
$items = [
['name' => 'David Charleston', 'member' => 1, 'active' => 1],
['name' => 'Blain Charleston', 'member' => 0, 'active' => 0],
['name' => 'Megan Tarash', 'member' => 1, 'active' => 1],
['name' => 'Jonathan Phaedrus', 'member' => 1, 'active' => 1],
['name' => 'Paul Jackson', 'member' => 0, 'active' => 1]
];
We can start by changing this array into a collection, add filters and tap into it
return collect($items)
->where('active', 1)
->tap(function($collection){
return var_dump($collection->pluck('name'));
})
->where('member', 1)
->tap(function($collection){
return var_dump($collection->pluck('name'));
});
Results #1
David Charleston, Megan Tarash, Jonathan Phaedrus, Paul Jackson
Result #2
David Charleston, Megan Tarash, Jonathan Phaedrus
Read more
- Laravel New - Laravel Collection “tap” Method
- tutsforweb - Tap In Laravel
- Taylor Otwell
- Laracast forum
- Freek.dev - Laravel's tap helper function explained