Amit Erandole Amit Erandole - 4 months ago 75
PHP Question

Laravel 5.2: Display a session flash message after user login/logout and registration

Working with the default setup generated after running

php artisan make:auth
, I am now wondering how do I control the flash messages I need to show to a user when he logs in.

So far I have tried adding this code to the default
AuthController
:

public function authenticated($request, $user)
{
flash('Welcome back ' . $user->username . ', you have been logged in');
}


But this causes too many redirects error in my Chrome browser. How do I flash custom messages without creating a custom
LoginController
or overriding the complete
login
method inside
AuthController
?

Answer

I had to override the following methods in my AuthController:

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $successmessage = 'you are now successfully registered!';
        flash()->overlay('Yes', $successmessage, 'success');
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        Auth::logout();
        flash()->info('Bye', 'You have been successfully logged out!');
        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /**
     * Function called after user logs in
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function authenticated() {
        $successmessage = 'Hej '.Auth::user()->name.', you are logged in!';
        flash()->success('Hello', $successmessage);
        return redirect()->intended($this->redirectPath());
    }

That's it! Note that I am using a custom flash setup. You can use the defaults or your own

Comments