Palzin Track
Get 15% off with code PTRACKSIGNUP15 

Laravel Diary Logo

Tips & Tricks

general
Table of Contents

Eloquent wherehas

// 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

  1. Artical by Muhammad Azeem

“tap” Method

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

  1. Laravel New - Laravel Collection “tap” Method
  2. tutsforweb - Tap In Laravel
  3. Taylor Otwell
  4. Laracast forum
  5. Freek.dev - Laravel's tap helper function explained

  1. Database Transactions in Laravel by Fideloper
  1. GitHub markdown docs

::Share it on::

Comments (0)

What are your thoughts on "Tips & Tricks"?

You need to create an account to comment on this post.

Related articles