Hooks in Laravel 5?

I am creating a package and want to use the hook function (the package should introduce some additional validation rules when a user updates a field in my application).

I managed to do this using an event system. What I am doing is passing the $ rules and $ request variable to the listener, I modify the $ rules variable and return it.

Would this be bad practice? What would be the recommended way to do this?

I mean, it works. I'm just not sure if this is the best way to do this.

Code below:

SettingsController.php (this is in the app / and where I check for updates)

public function update(Setting $setting, Request $request)
{
    $rules = [
        'package' => 'required|in:'.implode(config('app.packages'),','),
        'name' => 'required|max:255|alpha_dash|not_contains:-|unique:auth_setting,name,'.$setting->id.',id,package,'.$setting->package,
        'description' => '',
    ];

    // Is this bad??
    $rules = Event::fire(new SettingsWereSubmitted($request,$rules))[0];

    $v = Validator::make($request->all(),$rules);

Then in my package (packages / exchange / src / Listeners) I got this listener (ValidateSettings.php):

public function handle(SettingsWereSubmitted $event)
{
    if($event->request->package == 'exchange')
    {
        // Add rules

        $rules = [
            'fee' => 'required|decimal|min_amount:0|max_amount:1|max_decimal:8',
             'freeze_trade' => 'required|in:1,0',
        ];

        $event->rules['value'] = $rules[$event->request->name];

        return $event->rules;
    }

}
+4
1

 if($event->request->package == 'exchange')

, valid_if validation.

$rules = [
        'package' => 'required|in:'.implode(config('app.packages'),','),
        'name' => 'required|max:255|alpha_dash|not_contains:-|unique:auth_setting,name,'.$setting->id.',id,package,'.$setting->package,
        'description' => '',
        'fee' => 'required_if:package,exchange|decimal|min_amount:0|max_amount:1|max_decimal:8',
        'freeze_trade' => 'required_if:package,exchange|in:1,0',
    ];

: , Request , Request, Controller. . -, Http\Requests:

class UpdateSomethingRequest extends Requst
{

    public function rules()
    {
      return [
        'package' => 'required|in:'.implode(config('app.packages'),','),
        'name' => 'required|max:255|alpha_dash|not_contains:-|unique:auth_setting,name,'.$setting->id.',id,package,'.$setting->package,
        'description' => '',
        'fee' => 'required_if:package,exchange|decimal|min_amount:0|max_amount:1|max_decimal:8',
        'freeze_trade' => 'required_if:package,exchange|in:1,0',
      ];
    }

}

new-type , :

public function update(Setting $setting, UpdateSomethingRequest $request)
{
// Your request is already validated here so no need to do validation again
}
0

All Articles