Laravel Code Refactoring using when()

Laravel Code Refactoring using when()

Posted on:April 17, 2020 at 10:00 AM

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 have any comments or suggestion, feel free to share your thoughts.