Action that requires to be logged in

Maybe this is not a 100% Livewire question, but the idea is to show a page to users and to the guests in a same way, using the same route, but some actions on the page might need require be logged in. Like “:heart: Add to favorites” or maybe “:email: send a message”.
The functionality for logged users is pretty clear. How to redirect users to login page and back to the current page without adding special controllers and routes? Is this possible?

You can just use Laravel Directives

Blade

@guest
   <button>You must Login to Send a message</button>
@endguest

@auth
<button>Send Message</button
@endauth

component [controller]

if (Auth::check()) {
// do this
}

And so on …

@skywalker Right, this was clear for me.

My question was whether it is possible to make a simple action, that redirects guest to login and back to this page.

@guest
   <a title="You must Login to Send a message" href="{{route('login')}}">Send a message</a>
@endguest

But make sure that login will redirect user back to this page… :slight_smile:

You can do the following in your loginController if you are using the default laravel-ui scaffolding

// LoginController
public function __construct()
{
    $this->middleware('guest')->except('logout');
    $this->redirectTo = url()->previous();
}

or you can override ShowLoginForm

public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

P.S: I notice in many laravel project I made, after authenticate the user by logging in the app redirect me automatically to the previous URL, but how? I Have no Idea :smile:

Another Idea [not tested]
maybe you can make a middleware to check for specific URL parameter, after that it create a session name with the URL value and use this session in your login/register controller

For example:
in your blade

@guest
<a title="Authenticate your self to send a message" value="{{route('login', ['redirect' => Request::fullUrl()])}}">Send a message</a>
@endguest

in RedirectedIfHasRedirectionParameter middleware

// ...
if (request()->has('redirect')) {
    session()->put('redirect', request('redirect'));
}
return request($next);

//...

And Finally in your Login Controller

public function login()
{
// ....

 if (session()->has('redirect')) {
    $redirectionUrl = session()->get('redirect');
    session()->forget('redirect');
    return redirect()->back($redirectionUrl);
 }
}
1 Like