Loading image

Blogs / Programming

Mastering Conditional Logic in Laravel with when() and unless() Methods

Mastering Conditional Logic in Laravel with when() and unless() Methods

  • Asfia Aiman
  • 0 Comments
  • 512 View

Laravel’s power lies in its elegant syntax and advanced features. One of the most recent additions to Laravel 11.35.0 is the when() and unless() methods, part of the Conditionable trait. These methods simplify complex conditional logic, making your code cleaner, more readable, and easier to maintain.

In this guide, I’ll demonstrate how to use these methods in real-world scenarios to enhance your Laravel applications.

1. Dynamic Role Assignment Based on User Input

When building a user registration form, you often need to assign a role based on user input. Here's how you can streamline that with when().

Without when():

 
if ($request->has('role')) {
    $user->assignRole($request->input('role'));
}
 

With when():

 
$user->when($request->has('role'), function ($user) use ($request) {
    $user->assignRole($request->input('role'));
});
 

This approach ensures the role is only assigned if the role input is present.

2. Dynamic Validation Rules

In forms where certain fields are conditionally required, when() helps apply validation rules only when needed.

Without when():

$rules = ['email' => 'nullable'];

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

$request->validate($rules);
 

With when():

$request->when($request->has('newsletter'), function () use ($request) {
    $request->validate([
        'email' => 'required|email',
    ]);
});
 

This keeps the validation logic concise and readable.

3. Conditional Data Merging for Specific Operations

In an e-commerce app, you may want to apply a discount only if a valid coupon code is provided.

Without when():

$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);
 

With when():

$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);
 

4. Simplifying Conditional Logic for User Status

To display different messages based on user status, unless() makes the code much cleaner.

Without unless():

if (!$user->isActive()) {
    return "Your account is inactive. Please contact support.";
} else {
    return "Welcome back!";
}

With unless():

return $user->unless($user->isActive(), function () {
    return "Your account is inactive. Please contact support.";
})->otherwise(function () {
    return "Welcome back!";
});
 

5. Combining when() and unless() for Complex Flows

These methods can also be combined to handle multiple conditional flows in a streamlined manner.

$variable->when($user->isAdmin(), function ($variable) {
    return $variable->adminDashboard();
})->unless($user->isAdmin(), function ($variable) {
    return $variable->guestDashboard();
});
 

6. Payment Gateway Integration Based on User's Payment Method

When dealing with different payment methods, you can simplify the logic using when().

Without when():

if ($request->input('payment_method') == 'credit_card') {
    // Handle credit card payment logic
} elseif ($request->input('payment_method') == 'paypal') {
    // Handle PayPal payment logic
} elseif ($request->input('payment_method') == 'bitcoin') {
    // Handle Bitcoin payment logic
}
 

With when():

 
$request->when($request->input('payment_method') == 'credit_card', function () {
    // Handle credit card payment logic
})->when($request->input('payment_method') == 'paypal', function () {
    // Handle PayPal payment logic
})->when($request->input('payment_method') == 'bitcoin', function () {
    // Handle Bitcoin payment logic
});
 

7. Real Estate Property Price Calculation with Discounts

In real estate, you may need to apply discounts based on user input like being a first-time buyer or having a promo code.

Without when():

 
$price = $property->price;

if ($request->has('first_time_buyer')) {
    $price -= 5000;
}

if ($request->has('promo_code')) {
    $promo = PromoCode::where('code', $request->input('promo_code'))->first();
    if ($promo) {
        $price -= $promo->discount;
    }
}
return response()->json(['price' => $price]); 

With when():

$price = $property->price;

$price = $price->when($request->has('first_time_buyer'), function ($price) {
    return $price - 5000;
});

$price = $price->when($request->has('promo_code'), function ($price) use ($request) {
    $promo = PromoCode::where('code', $request->input('promo_code'))->first();
    return $promo ? $price - $promo->discount : $price;
});

return response()->json(['price' => $price]);
 

8. Medical Appointments with Insurance Verification

For healthcare applications, when() simplifies complex logic related to insurance verification.

Without when():

$payment = $appointment->cost;

if ($request->has('insurance_provider')) {
    $insurance = Insurance::where('provider', $request->input('insurance_provider'))->first();
    if ($insurance) {
        $payment -= $insurance->coverage;
    }
}

return response()->json(['payment' => $payment]);
 

With when():

$payment = $appointment->cost;

$payment = $payment->when($request->has('insurance_provider'), function ($payment) use ($request) {
    $insurance = Insurance::where('provider', $request->input('insurance_provider'))->first();
    return $insurance ? $payment - $insurance->coverage : $payment;
});

return response()->json(['payment' => $payment]);
 

Conclusion

By using when() and unless(), you can streamline your Laravel code, making it more readable, maintainable, and elegant. Whether you're working with user roles, validation rules, e-commerce platforms, real estate applications, or healthcare systems, these methods can simplify complex conditional logic and enhance the clarity of your code.

  • Programming
Asfia Aiman Author

Asfia Aiman

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

The Power of Feedback: How Regular Check-Ins Can Transform Employee Performance and Engagement

The Power of Feedback: How Regular Check-Ins Can Transform Employee Performance and Engagement

rimsha akbar
/
Human Resource

Read More
Top Companies Driving Emerging Technologies in 2024

Top Companies Driving Emerging Technologies in 2024

showkat ali
/
Technology

Read More
The Rise of the First AI Software Engineer | devin cognition

The Rise of the First AI Software Engineer | devin cognition

showkat ali
/
Programming

Read More
DeepSeek vs. ChatGPT: Which AI Chatbot is Better for You?

DeepSeek vs. ChatGPT: Which AI Chatbot is Better for You?

showkat ali
/
Technology

Read More
Simulating the Iron Dome Defense System with Python: A Complete Guide

Simulating the Iron Dome Defense System with Python: A Complete Guide

showkat ali
/
Programming

Read More
How to Publish API Route File in Laravel 11

How to Publish API Route File in Laravel 11

showkat ali
/
Programming

Read More