$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.
Leave a reply