Posts Learn Components Snippets Categories Tags Tools new About
/

Map Eloquent Results in Laravel

Learn how to map your eloquent results in Laravel to loop through the data and perform your desired action

Created on Aug 13, 2021

151 views

When you query your Eloquent model in Laravel you can directly get the Collection instance and make use of the "map()" method to query your data. By doing so you can pass in the function which will accept the data that's being looped through by the method.
$posts = Post::get()->map(function ($post) {
    dd($post->title);
});

By making use of "map()" method, your code is much more expressive and easier to read. Do note that you need to call the "get()" from the model to get the Collection instance. If you are using "all()" then the eloquent will return an array and you can't call the "map()" method.

Before Using "map()"
If you are not using the "map()" your typical code for looping will look as follow.
$posts = Post::where('published', true)
    ->orderByDesc('title')
    ->get();

foreeach($posts as $post) {
    dd($post->title);
}

After Using "map()"
Now when you use the map method it's more straightforward.
$posts = Post::where('published', true)
    ->orderByDesc('title')
    ->get()
    ->map(function ($post) {
        dd($post->title);
    })

Do note that you can also call other Laravel collection methods as you see fit for your use case.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Map Eloquent Results in Laravel

)