Vit
Vit

Reputation: 488

laravel 5.2 redirect after registration by id

I've found here some examples, but they are not answering how to redirect registered user to his own profile by id.

protected $redirectPath = '/profile/view/'.$user->id; Did not help. I have a project where users are being authorized without email confirmation and they are sent to /home after registration.

Route to user profile is: /profile/view/id (id is unique of course). I managed to send them there after login (in AuthController :

public function authenticated($request,$user)
{ 
    return  redirect('/profile/view/'.$user->id);
} 

but redirect to profile after registration I can't handle.

Upvotes: 0

Views: 967

Answers (1)

Kyslik
Kyslik

Reputation: 8385

Approach 1.

Let users view their own profile without ID.

route (make ID optional):

Route::get('profile/view/{id?}', ...);

controller:

public function view($id = null) {
    if (is_null($id) { //set id of currently signed in user if id == null
        $id = Auth::user()->id; 
    }

    //continue as before

}

Approach 2.

Modify routes so redirect happens to correct url.

Note: order of routes is important

Route::get('profile/view', function() {
    return redirect()->route('profile.view', ['id' => Auth::user()->id]);
});

Route::get('profile/view/{id}', ...)->name('profile.view');

Note: in both approaches auth middleware is a must, else you going to get error if user is not logged in (PHP error: Trying to get property of non-object on line X)

With both approaches you just redirect user to profile/view:

  1. is shown profile (without ID in URL)
  2. is redirected to proper url profile/view/ID.

Upvotes: 1

Related Questions