I am new to Laravel and would like to know the best pracitse method to handle duplicate code.
I have nearly in all functions of my api-controllers this code at beginning:
// Validate parameters
$validator = Validator::make($request->all(), $this->validationRules);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
So normally I would put it in some function. But this code also used in lot of other controllers. so this function should be called also by other controllers.
What is best practise to handle that in Laravel 5? My first idea was to make some own Controller with this function and my other controllers would extend this.
Like:
class MyController extends Controller
{
protected function handleFailByPrameter($params)
{
....
}
}
class Api1Controller extends MyController
{
public function apicall1()
{
$this->handleFailByPrameter($this->validationRules());
}
}
But maybe there are some other methods to handle that kind of things?