xnor
xnor

Reputation: 31

refresh page after updated model - Laravel

I want to refresh current page after any user update

I'm trying to do something like that in User Model :

 public static function boot()
    {
        self::updated(function ($model) {
            return back(); //or redirect(Request::url())

        });
    }

but it wasn't working. How can I refresh the page if any user updated

Upvotes: 2

Views: 12768

Answers (1)

Flame
Flame

Reputation: 7628

In general, the model event functions creating/created/updating/updating/saved/saving should only ever return false or nothing (void). Returning false in for instance updating (that is: before the model is persisted in the database) cancels the model update (this works for all propagating events, see https://laravel.com/docs/9.x/events#stopping-the-propagation-of-an-event).

To "refresh" the current page after a user update, you have to be more specific about what you require. The back() function that you use (or the aliases redirect()->back() or even app('redirect')->back()) is (to my knowledge) to be used in controllers and it uses the Referer header or a property in the user's session to determine to which page to send the client to. This is most often used with validation errors, so that you can send the user back to the page they came from along with any possible validation error messages.

Using back() (or any other request completions like return response()->json('mydata')) inside events is wrong and it doesn't even work since the result of such events is not being used to complete the request. The only valid thing you "could" do is to try validation inside an event, which in turn could throw ValidationExceptions and is therefore automatically handled.

What you should do is use the controller method that actually handles the request that updates the user:

// UserController.php
/** (PUT) Update a user */
public function update(Request $request, User $user)
{
    if($user->update($this->validate($request, [/* validations */])) {
        return redirect()->back();
        // or even be explicit and use `return redirect()->route('users.show', $user);`
    }
    // `update()` returned false, meaning one of the model events returned `false`
    // (there is no exception thrown here).
    session()->flash('alert-info', 'Something went wrong');
    return redirect()->back();
}

Upvotes: 0

Related Questions