Good day, friends. Help me figure it out, otherwise I’ve already broken my head ... Task - after authorization, on the / login page you need to redirect to the user’s page with id in the URL. An example below.

Now I have registered with LoginController.php:

protected $redirectTo = '/profile'; 

That is, redirect to the / profile page, but you need to do something like this:

 protected $redirectTo = '/profile/{$id}'; 

That is, the URL of the logged in user is added to the URL.

In routers / web.php I have written this:

 Route::get('profile/{id}', 'HomeController@index'); 

That is, when you go to the / profile / user-id page, a page with information about the user opens with the id specified in the URL. But in LoginController.php it doesn't work like this ... when I write protected $redirectTo = '/profile/{$id}';

then everything works, but only the URL of this type / profile /% 7Bid% 7D

What is wrong doing? I understand that ID is somehow perceived as a string, not a number.

    2 answers 2

    Let's just look at the App\Http\Controllers\Auth\LoginController class, this class uses the feature: AuthenticatesUsers ,

    Now let's take a look at this feature, it in turn uses 2 more features: RedirectsUsers , ThrottlesLogins

    From your question, it is immediately clear that we need the first one, let's look at it:

     namespace Illuminate\Foundation\Auth; trait RedirectsUsers { /** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { if (method_exists($this, 'redirectTo')) { return $this->redirectTo(); } return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home'; } } 

    The only method implemented in it is redirectPath, which checks if there is a redirectTo () method, if it is not there, it will attempt to switch to the redirectTo property, if not, and then go to /home

    It remains to create a method in the class LoginController:

     protected function redirectTo(){ return url('/profile/',auth()->user()->id); } 
    • What you need, thanks! - G_Java

    The documentation says that if you need to use some kind of logic for the redirect, then the protected $redirectTo property can be replaced with the method

     protected function redirectTo() { // Получить $id return '/profile/' . $id; }