Laravel, a renowned PHP framework, boasts an elegant syntax and powerful features. Introduced in Laravel 11.35.0, the when()
and unless()
methods (part of the Conditionable
trait) offer a more concise and efficient approach to conditional logic, significantly improving code readability and maintainability. This article explores practical applications of these methods in real-world Laravel scenarios.
Consider a user registration form where users select a role. Post-registration, different permissions are assigned based on the chosen role.
when()
:<code class="language-php">if ($request->has('role')) { $user->assignRole($request->input('role')); }</code>
when()
:<code class="language-php">$user->when($request->has('role'), function ($user) use ($request) { $user->assignRole($request->input('role')); });</code>
The when()
method neatly encapsulates role assignment, executing only when a role is provided.
In a form, certain fields might require validation only under specific conditions. For instance, the email field is mandatory only if the user opts into a newsletter.
when()
:<code class="language-php">$rules = [ 'email' => 'nullable', ]; if ($request->has('newsletter')) { $rules['email'] = 'required|email'; } $request->validate($rules);</code>
when()
:<code class="language-php">$request->when($request->has('newsletter'), function () use ($request) { $request->validate([ 'email' => 'required|email', ]); });</code>
This cleaner approach leverages when()
for conditional validation.
In e-commerce, discounts might apply only with a valid coupon code. Let's dynamically merge discount data.
when()
:<code class="language-php">$data = [ 'total_price' => $cart->totalPrice(), ]; if ($request->has('coupon_code')) { $coupon = Coupon::where('code', $request->input('coupon_code'))->first(); if ($coupon) { $data['discount'] = $coupon->discount_amount; } } return response()->json($data);</code>
when()
:<code class="language-php">$data = [ 'total_price' => $cart->totalPrice(), ]; $data = $data->when($request->has('coupon_code'), function ($data) use ($request) { $coupon = Coupon::where('code', $request->input('coupon_code'))->first(); if ($coupon) { $data['discount'] = $coupon->discount_amount; } return $data; }); return response()->json($data);</code>
This demonstrates a more streamlined, chainable approach to conditional discount application.
Sending different messages based on user activation status can be simplified using unless()
.
unless()
:<code class="language-php">if (!$user->isActive()) { return "Your account is inactive. Please contact support."; } else { return "Welcome back!"; }</code>
unless()
:<code class="language-php">return $user->unless($user->isActive(), function () { return "Your account is inactive. Please contact support."; })->otherwise(function () { return "Welcome back!"; });</code>
unless()
condenses the conditional logic into a single, readable return
statement.
when()
and unless()
For complex scenarios, combine when()
and unless()
to manage various user types (admin, guest, etc.) and display appropriate content.
<code class="language-php">$variable->when($user->isAdmin(), function ($variable) { return $variable->adminDashboard(); })->unless($user->isAdmin(), function ($variable) { return $variable->guestDashboard(); });</code>
The article continues with similar concise examples demonstrating the use of when()
and unless()
in:
These examples highlight the versatility and elegance of Laravel's when()
and unless()
methods across diverse applications. By utilizing these methods, developers can write cleaner, more maintainable, and more readable Laravel code.
The above is the detailed content of Mastering Conditional Logic in Laravel with `when()` and `unless()` Methods: Real-Life Examples. For more information, please follow other related articles on the PHP Chinese website!