Write Cleaner Laravel Code Using the when() Helper

Write Cleaner Laravel Code Using the when() Helper

Laravel is known for its beautiful, expressive syntax. One of the underrated gems in its collection of helpers is the when() method. A small but powerful helper, when() can greatly improve the readability and maintainability of your code, especially when it comes to performing conditional logic inside collections, queries, and many other complex situations.

Laravel Development Services

In this blog, we will discuss how Laravel’s when() method works to perform conditional tasks with clean and concise code.

Prerequirement:

  • Composer (latest Version)
  • Laravel version 12

Steps to Use when() Helper in Laravel:

Step 1: Create a New Laravel Project

composer create-project laravel/laravel when-demo-project
cd when-demo-project

Step 2: Create Your Controller

php artisan make:controller DemoController

This will create a controller at app/Http/Controllers/DemoController.php.

Now, open the file and update the checkCondition() method like this:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\View;

class ViewController extends Controller
{
    public function checkCondition()
    {
        $currentUser = "farmers"; 

        return when($currentUser === 'farmers', function () {
            return view('farmerView');
        }, function () {
            return view('defaultView');
        });
    }
}

Step 3: Add the Route

Route::get('/', [DemoController::class, 'checkCondition']);

Step 4: Create Blade View Files

php artisan make:view farmerView
php artisan make:view defaultview

resources/views/farmerView.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>farmers</title>
</head>
<body>
    <h1>Welcome, farmers</h1>
</body>
</html>

resources/views/defaultView.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Guest page</title>
</head>
<body>
    <h1>Please login</h1>
</body>
</html>

Step 5: Test It

php artisan serve

Now open this URL in your browser:

http://localhost:8000

Output:

If the current user is a farmer, then you will see:

 “Welcome, farmers”

If the current user is not a farmer, then you will see:

 “Please login”

Conclusion

With the help of Laravel’s when() function, we can expressively and readably combine decision-making and execution into a single call, thereby greatly simplifying the complexity of conditional logic.

If you have any questions, let me know in the comments.

Hire Laravel Developer

FAQ

  1. What is Laravel?

With its expressive and elegant syntax, Laravel is a web application framework that offers a starting point and foundation for PHP web application development.

  1. Why Use Laravel?

Laravel has a rich set of features, including an expressive database abstraction layer (Eloquent), powerful templating engine (Blade), built-in authentication and authorization, routing system, queues, scheduled jobs, and a command-line interface (Artisan CLI). It offers a variety of tools to aid in development and is centered on the developer experience.

  1. What is the when() helper function in Laravel?

Laravel’s when() helper is a conditional tool that lets you do something only if a certain condition is met. It makes code more expressive and cleaner, particularly in pipelines, collections, and query builders.

Previous Article

How to Use Flash Messages in Laravel 12 with Example

Next Article

Magento 2: How to Add a Column to Products in Category Grid

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨