Reputation: 63
I am Newbie. I'm trying to return a view of member profile
At the moment, the user profile is accessible by its ID, like so
profile/7
I would like to access it through the name that I've created
profile/John
this is my route
Route::get('profile/{id}', 'ProfilController@tampilkanID');
this is my controller
public function tampilkanID($id)
{
$auth = Auth::user()->id;
$users=\App\users::all()->whereNotIn('id',$auth);
$tampilkan = Users::find($id);
return view('tampilkan', compact('tampilkan', 'users'));
}
and this how i call it in my blade
@foreach($users as $user)
<tr>
<td><a id="teamname" href="{{ url('profile',$user->id) }}" target="_blank">{{$user->name}}</a></td>
</tr>
@endforeach
thank you
Upvotes: 1
Views: 5234
Reputation: 1541
Just Customise you RouteServiceProvider as Like below :
public function boot()
{
parent::boot();
Route::bind('user', function ($value) {
return App\User::where('name', $value)->first() ?? abort(404);
});
}
or
customise your route key in model.
For eg :
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'name';
}
Route :
Route::get('users/{user}', function ($user) {
return view('user.show', compact('user'));
});
Upvotes: 0
Reputation: 2800
You can use laravel Route Model Binding
.
What is Route Model Binging?
Route model binding in Laravel provides a mechanism to inject a model instance into your routes.
How can I use it?
Pass object rather then id
like
Route::get('users/{user}', function ($user) {
return view('user.show', compact('user'));
});
In your User.php
define getRouteKeyName
then return whatever you want as a route
public function getRouteKeyName()
{
return 'name'; //this will return user name as route
}
so your route will be users/name
For more information have a look at laravel documentation https://laravel.com/docs/5.5/routing#route-model-binding
Upvotes: 0
Reputation: 1213
try this:
Route:
Route::any('profile/{name}', 'ProfilController@index')->name('profile.index');
Controller:
public function index(Request $request, $name)
{
$user = User::where('name', $name)->first();
if(isset($user))
return view('tampilkan', ['user' => $user]);
return "user not found!";
}
Blade:
@foreach($users as $user)
<tr>
<td><a id="teamname" href="{{ route('profile.index',['name' => $user->name]) }}" target="_blank">{{$user->name}}</a></td>
</tr>
@endforeach
Suggestion:
if you're doing this, you should also set "name" column to "unique" in users
table in order to get exactly one user each time and not confuse users to each other.
Upvotes: 3