Laravel Code Refactoring using when()

16 Apr, 2020

Today, I will show you a code refactoring tricks by using ->when() to make your code better readable and standard.

Consider, I have given the following code-


    $user = \App\User::latest();

    if (request()->location) {
        $user->where('location', "LIKE", "%". request()->location ."%");
    }

    if (request()->name) {
        $user->where('name', "LIKE", "%". request()->name ."%");
    }

    return $user->get();

It basically takes the value of location and name from the URL and applies condition if those values are not empty.

It works fine. No issues what so ever.

Wait... are you satisfied with this code? Can we make this code better in somehow?

Well, personally I prefer to use ->when() instead of slicing my query. Here is my approach.


return \App\User::latest()
        ->when($location = request()->location, function($q) use($location){
            return $q->where('location', "LIKE", "%". $location ."%");
        })->when($name = request()->name, function($q) use($name){
            return $q->where('name', "LIKE", "%". $name ."%");
        })->get();

It's basically checking the first parameter in when(). If the first parameter is true, then it goes to Closure and apples the condition.

Of course, it depends on your taste, however, I feel this is one is the better approach over the previous example. It looks clean and more readable to me.

If you are visual learner, you can check it out this link https://youtu.be/FCMjOlnTjSM

If you have any comments or suggestion, feel free to share your thoughts.

Hello. I’m Thouhedul Islam. Some people also know me as Suchi.

I am a Full-stack Developer. I love to play with PHP especially Laravel, JavaScript, MySql, and latest web technology. Currently, I am working for CartX as my day time job.

At night I love to solve problems for the community. I love to be active at Laracasts.