Home / Snippets / Map Eloquent Results in Laravel
Map Eloquent Results in Laravel cover

Map Eloquent Results in Laravel

395

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this