Performance: Mail templates
This affects the server response time and initial page load speed when sending emails with rendered templates.
Jump into concepts and practice - no test required
<?php // In controller $orders = $user->orders()->with('product')->get(); Mail::send('emails.welcome', ['user' => $user, 'orders' => $orders], function($message) use ($user) { $message->to($user->email)->subject('Welcome!'); }); // Blade template uses preloaded data @foreach($orders as $order) {{ $order->product->name }} @endforeach
<?php // In controller Mail::send('emails.welcome', ['user' => $user], function($message) use ($user) { $message->to($user->email)->subject('Welcome!'); }); // Blade template with heavy loops and inline queries @foreach($user->orders as $order) {{ DB::table('products')->where('id', $order->product_id)->first()->name }} @endforeach
| Pattern | DB Queries | Template Render Time | Email Size | Verdict |
|---|---|---|---|---|
| Inline queries in template | Multiple per item | High (500ms+) | Medium | [X] Bad |
| Preloaded data passed to template | Single query | Low (100ms) | Medium | [OK] Good |
| Heavy images and CSS | N/A | Low | Large (100+ KB) | [X] Bad |
| Minimal CSS and no large images | N/A | Low | Small (<20 KB) | [OK] Good |
php artisan make:mail MailName --markdown.$this->name inside the markdown template?class WelcomeMail extends Mailable {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function build() {
return $this->markdown('emails.welcome')->with(['name' => $this->name]);
}
}new WelcomeMail('Alice'), what is $name in the template?$this->name to the passed value 'Alice'.with() method passes ['name' => $this->name], so 'Alice' is passed as 'name'.class NotifyUser extends Mailable {
public function build() {
return $this->markdown('emails.notify')->with('user', $user);
}
}$user is used but not defined or passed to the method.markdown() is correct; with() accepts key-value pairs or array, so usage is okay if $user existed.with() or public properties.with(['products' => $products]) in the build() method correctly uses with() to pass the products array. Pass products as a constructor argument but do not use with() misses passing data to template. Call markdown('emails.products', $products) directly uses wrong markdown method signature. Set a private property $products but do not pass data sets property but does not pass data.