How to Use JavaScript Array Filter() With an Examples
Read More
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.
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.
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.
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);
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!";
});
when()
and unless()
for Complex FlowsThese 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();
});
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
});
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]);
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]);
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.
Recent posts form our Blog
0 Comments
Like 1