#1 — Laravel & More: What I’ve learned this week

There is a lot of information circulating on the Internet and it can be very time-consuming to look everywhere, stay up to date and discover new things. Here’s why I’ll — try to — write a weekly digest of everything I find scrolling here and there.
Some of these pieces of information were found long before I had the idea to make an article out of them, which is why I can’t tag any author of the original posts. This will be corrected in each future article of this “series”!
PS: This series primarily focuses on Laravel and web development.
Reducing your request’s memory usage.
/**
* Limit memory usage when loading relations
* by selecting specific attributes.
*/
User::with('comments:id,user_id,content')->get();Laravel 9 selected() blade directive.
/*
* Laravel 9 is shippes with a new @selected
* Blade directive.
*/
<select name="countries">
<option value="" >Select a country</option>
@foreach($countries as $country)
<option value="{{ $country->id }}" @selected($country-is($user->country)) >
{{ $country->name }}
</option>
@endforeach
</select>Encrypt/decrypt your model’s attributes.
/**
* Data can be automatically Encrypted/Decrypted using Laravel's
* 'encrypted' cast.
*/
Class CreditCard extends Model
{
protected array $casts = [
'number' => 'encrypted',
];
}
/**
* It is worth reminding that encrypted data will be larger than 'raw'
* data, so be sure to store them in an appropriate column type.
*/
Class CreateCreditCardsTable extends Migration
{
public function up(): void
{
Schema::create('credit_cards', function (Blueprint $table) {
$table->id();
$table->text('number');
...
});
}Split your routes into separate files.
/**
* Laravel provides an easy way to split routes in separate files.
*/
Class RouteServiceProvider extends ServiceProvider
{
public function boot()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('route/web.php'));
Route::middleware('api')
->namespace($this->namespace)
->prefix('api/v1')
->group(base_path('route/api-v1.php'));
Route::middleware('api')
->namespace($this->namespace)
->prefix('api/v2')
->group(base_path('route/api-v2.php'));
Route::middleware('api')
->namespace($this->namespace)
->prefix('webhooks')
->group(base_path('route/webhooks.php'));
}
}The pluck() method works with your model’s relations!
/**
* pluck() is a method that retrieves all values for a given key, but
* did you know it also works with relations ?
*/
$users->pluck('comments')->each(fn(Comment $comment) => ...);Use the validator’s “bail” attribute to stop validation at the first failure.
/**
* When validating a request, you can ask Laravel to stop at
* the first failure using the 'bail' attribute.
*/
public function rules(): array
{
/**
* Here, Laravel's validator will not run a query to check
* if a user exists if a previous validation fails.
*/
return [
'id' => ['bail', 'required', 'integer', 'exists:users,id'],
];
}Hope you learned something new!