dimanche 23 juillet 2017

Laravel best practice from getting db data from validation into controller method?

I have a controller method like so:

public function activate(AuthActivateRequest $request)
{
    $token = Token::create([
        'user_id' => $request->get('user_id'),
        'type' => 'activate'
    ]);

    return response([
        'status' => 'success',
        'msg' => 'Activation email resent.'
    ], 200);
}

I try to keep as much logic as I can in a Request object so that it can handle all the error outputs. My concern is that I have to write a bunch of custom validations to set these parameters to avoid making multiple calls to the db for the same value.

Say we validate an email value from the activate token request.

Validator::extend('user_exists', function ($attribute, $value, $parameters, $validator) use ($self)
{
    $user = User::where('email', $value)->first();

    if ($user) {               
        $self->request->add(['user_id' => $user->id]);

        return true;
    }

    return false;
});

I was wondering if there was some way to inject the user model in directly like with route/model binding. But at this point it's too late.

I'm wondering what the best way to handle this is?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire