php - Prevent logout auth laravel

107

is there any way to listen the logout event and take decisions like redirect on auth laravel? I know there are some login/logout listeners but redirects are not working:

class LogSuccessfulLogout
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Logout  $event
     * @return void
     */
   public function handle(Logout $event)
   {
    if($event->user) {


        $new = Auth::user()->cars()->where('status', 1)->count();
        $inProgress = Auth::user()->cars()->where('status', 2)->count();

        if($new > 0 || $inProgress > 0){
            redirect('/');
        }
    }

  }
}
444

Answer

Solution:

This is the default logout function called in in the default Laravel 5.2 AuthController

public function logout()
{
    Auth::guard($this->getGuard())->logout();
    return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}

You can therefore set theredirectAfterLogout property to change the redirect url with the following code in your AuthController,

private $redirectAfterLogout = '/new-logout-redirect';

or you can choose to simply override the logout function. Redirects will not work directly from your Listener.

Here's the modified logout function with your logic which you can place in your AuthController,

public function logout()
{
    Auth::guard($this->getGuard())->logout();

    $new = Auth::user()->cars()->where('status', 1)->count();
    $inProgress = Auth::user()->cars()->where('status', 2)->count();

    if($new > 0 || $inProgress > 0){
        return redirect('/');
    }

    return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}

People are also looking for solutions to the problem: Replace first matching line in string php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.