5

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

owenmelbz
  • 6,180
  • 16
  • 63
  • 113

3 Answers3

21

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); }

Brad Bird
  • 737
  • 1
  • 11
  • 30
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
3

You can use the request helper fuction as:

if( request()->has('password') ){
    $user->password = bcrypt(request()->get('password'));
}
Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
1

As an alternative to the other two answers, you can pass the request through to the function:

User::created(function(User $user) use ($request) {
aynber
  • 22,380
  • 8
  • 50
  • 63