Using collection method filter() and map() on eloquent queries instead of using loop and if statement

We are not using collection method where() for the sake of this example for using collection methods filter() and map()

Suppose there is a relation Post belongsTo User and after Post eloquent query you want to get post title only for user id 2.

This can be achieved typically with following snippet.

Step 01: Eloquent Fetching without using relation

$posts = Post::all();

Step 02: loops, if and array operations

$title = [];
foreach( $posts as $post ) {
    if( $post->user_id == 2 ) {
        $title[] = $post->title;
    }
}

Now if we were to use collection methods filter() and map() avoiding loop, if statement and array operations, we can achieve this same result like below

Step 01: Eloquent Fetching without relation

$posts = Post::all();

Step 02: Using filter and map methods

$posts = $posts->filter( function( $post ) ) {
    return $post->user_id == 2;
})->map( function( $post ) ) {
    return $post->title;
});

Related Posts


Using collection method reduce()