Higher order messages in Laravel

Categorized as Laravel Tagged

Hello friends! In Laravel, you can utilize the shortcut for “higher order messages” that come with collections. This is extremely useful for performing common actions. See the code below:

use App\Models\Post;

// Collect posts that are marked as "inPromotion"
$posts = Post::where('inPromotion', true)->get();

// ❌ You could  it like this
foreach($posts as $post) {
  $post->generatePromoBanner;
}

// ✅ You should do it like this
$posts->each->generatePromoBanner();

Leave a reply

Your email address will not be published.