2

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?

Andi S.
  • 317
  • 1
  • 11

3 Answers3

5

You may create a validation function in your helper this will help you do that and then call this new function from anywhere in your laravel app(literally anywhere). Second thing you can do is create custom requests which will validate your data before it is passed to your function in the following way :

first generate a new requests class from artisan

php artisan make:request ExplicitRequestName

this will create a new file named ExplicitRequestName.php under app/Http/Requests folder open it, toggle false to true in your authorize function and then define your validation rules in following manner:

public function rules()
{
    return [
        'email' => 'required',
        'password' => 'required',
    ];
}

call this requests object in your function :

public function someFunction(Requests\ExplicitRequestName $request)
{
}
Community
  • 1
  • 1
Khan Shahrukh
  • 6,109
  • 4
  • 33
  • 43
3

Laravel 5.1 has a method attached to the Controller:

$this->validate($request, [your rules]);

It will redirect back with errors if anythings wrong, or send an error response if it's ajax.

To not defined your rules in every method, you can set in your models:

public static $rules = ['Your rules']

Then you can simply do your validation in your controllers, forexample:

$this->validate($request, Post::rules);
Iamzozo
  • 2,341
  • 18
  • 21
0

I think you are already on the right track. I implemented the validation and authentication for every API this way, although on laravel 4 .

Biplab
  • 1