Best place to add business logic in Laravel

August 30th, 2020 — 2 min read

Best place to add business logic in Laravel

Greeting!
While working on Laravel i couldn’t find any proper place to add my business logic. Also it is not mentioned anywhere in the docs and they let user add business logic on their own. Many people use Repository pattern to add business logic but i don’t want to use repository pattern. So i found a better place that seem to be related to other parts. Let me show you where it is.

Laravel gives you a feature called Form Request Validation. You can see here you can define validation rules and error messages here and call this in controller like this for example.

public function store(SaveCategoryRequest $request)
{

$request->validated();

// other stuff
}

So i thought instead of calling validated method in controller i should add handle method in form request and move validation call in something like this.

public function handle(){

$data = $this->validated();

// my business logic
}

and change the call in controller

public function store(SaveCategoryRequest $request)
{
$response = $request->handle();

return response()->json($response);
}

Now at this point you may be wondering how we can access request data in handle method since we are not passing request in handle method. So the answer is $this is our friend. Remember, we are in the context of BaseRequest so instead of $request we can use $this inside handle method.

$params = $this->all()

Hope this helps someone.