Search code examples
phplaravelrequestobservers

Using Request within Eloquent Model Observer


In Laravel 5.3, we're trying to create a form, which the user can update their profile details, including a new password.

However we want to only set the password if its been submitted.

We're using a CRUD framework which handles the updating of the models, and we don't want to roll our own update(Request $request) method.

We're aware that you can register model observers similar to

User::created(function(User $user){

});

We were hoping to achieve something similar to

User::created(function(User $user){

    if( $request->has('password') ){
        $user->password = bcrypt($request->input('password'));
    }

});

However, when we access $request, its completely empty. e.g if we do dd($request->all()); its an empty array, however if we dump out dd($_POST); we get everything.

I assume this is because of the order things are loaded, and the request system hasn't yet loaded.

Is there a way we can get the request without accessing the $_POST directly?

Thanks


Solution

  • Laravel 5.3+

    request() helper should work for you:

    if (request()->has('password')) {
        $user->password = bcrypt(request()->password);
    }
    

    You can access property with:

    request()->password
    request()->get('password')
    request('password')
    

    Lumen 5.3+

    The request() helper is not available in Lumen so you will need to use the IoC container.

    app('Illuminate\Http\Request')

    Example:

    if (app('Illuminate\Http\Request')->has('password')) { $user->password = bcrypt(app('Illuminate\Http\Request')->password); }