Home > Backend Development > PHP Tutorial > Mastering Conditional Logic in Laravel with `when()` and `unless()` Methods: Real-Life Examples

Mastering Conditional Logic in Laravel with `when()` and `unless()` Methods: Real-Life Examples

Mary-Kate Olsen
Release: 2025-01-16 16:06:10
Original
738 people have browsed it

Mastering Conditional Logic in Laravel with `when()` and `unless()` Methods: Real-Life Examples

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.

1. Dynamic Role Assignment Based on User Input

Consider a user registration form where users select a role. Post-registration, different permissions are assigned based on the chosen role.

Without when():

<code class="language-php">if ($request->has('role')) {
    $user->assignRole($request->input('role'));
}</code>
Copy after login

With when():

<code class="language-php">$user->when($request->has('role'), function ($user) use ($request) {
    $user->assignRole($request->input('role'));
});</code>
Copy after login

The when() method neatly encapsulates role assignment, executing only when a role is provided.

2. Dynamic Validation Rules

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.

Without when():

<code class="language-php">$rules = [
    'email' => 'nullable',
];

if ($request->has('newsletter')) {
    $rules['email'] = 'required|email';
}

$request->validate($rules);</code>
Copy after login

With when():

<code class="language-php">$request->when($request->has('newsletter'), function () use ($request) {
    $request->validate([
        'email' => 'required|email',
    ]);
});</code>
Copy after login

This cleaner approach leverages when() for conditional validation.

3. Conditional Data Merging

In e-commerce, discounts might apply only with a valid coupon code. Let's dynamically merge discount data.

Without 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>
Copy after login

With 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>
Copy after login

This demonstrates a more streamlined, chainable approach to conditional discount application.

4. Simplifying User Status Logic

Sending different messages based on user activation status can be simplified using unless().

Without unless():

<code class="language-php">if (!$user->isActive()) {
    return "Your account is inactive. Please contact support.";
} else {
    return "Welcome back!";
}</code>
Copy after login

With 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>
Copy after login

unless() condenses the conditional logic into a single, readable return statement.

5. Combining 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>
Copy after login

Further Examples (Briefly Summarized):

The article continues with similar concise examples demonstrating the use of when() and unless() in:

  • Payment Gateway Integration: Selecting payment logic based on user's chosen method.
  • Real Estate Price Calculation: Applying discounts based on first-time buyer status or promo codes.
  • Medical Appointments: Adjusting payment based on insurance coverage.
  • Bitcoin Price Adjustment: Adding fees based on market volatility.
  • E-commerce Product Availability: Determining shipping fees based on location.
  • Medical Treatment Plans: Assigning treatment plans based on patient conditions.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template