Przemek
Przemek

Reputation: 822

Laravel using user id in route

So I have a route profile/{user_id}

How do I redirect user to that URL when they click on link?

Here's my controller:

{
    function checkid($user_id) {
      if (Auth::check())
      {
        $user_id = Auth::id();
        return view('profile', [
        'id' => $user_id
        ]);
      }
    }
}

Upvotes: 0

Views: 2858

Answers (2)

bashleigh
bashleigh

Reputation: 9314

Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!

<?php

    namespace App\Http\Controllers;

    class RandomController extends Controller {
        public function index()
        {
            return view('profile');//use auth facade in blade.
        }
    }

In your routes use a middleware to prevent none authenticated users from reaching this method

<?php

Route::group('/loggedin', [
    'middleware' => 'auth',
], function() {

    Route::get('/profile', 'RandomController@index')->name('profile.index');

});

Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!

<h1>Hi! {{Auth::user()->name}}</h1>
<a href="{{route('profile.index')}}">View profile</a>

Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.

if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).

Let me know if you need help with anything else.

Upvotes: 2

Robert
Robert

Reputation: 5963

You can redirect with the redirect() helper method like this:

return redirect()->url('/profile/' . $user_id);

But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.

Upvotes: 0

Related Questions