I am making a website which will have user login. Login form now leads to admin panel if your role is admin
(route is behind admin
middleware), and it leads back to home page if your role is user
. Back on the home page you have the ability to see your profile page and add a product (which is behind auth
middleware).
My question is what is the best approach to form my routes?
If I make site.com/user/{id}
route, user ID's will be exposed to each user which logs in, as well as for example editing a product with site.com/user/{id}/product/{product_id}
.
I see some security issues here and am wondering if a better solution is making site.com/profile
route which will in turn in controller take Auth::user()
not exposing ID's in the process?
Add your route without the ID and use Auth::user()
It's best practice and makes your routes simpler
Public function profile(){
$user = Auth::user();
return view('profile', compact('user');
}
The above code is more straight forward than this:
Public function profile($id){
$user = User::find($id);
//prevent authenticated from viewing other users
if($user == Auth::user()){
return view('profile', compact('user');
}else{
//return something else
}
}
If you are worried about exposing user ID you can try use something like hashids, where ID will be encoded.
Here you go:
encode the id
and product_id
with base64_encode()
Example pass the id
and product_id
in url by encoding with base64_encode()
and when you want to use it use like this:
Route::get('user/{id}/product/{product_id}', function($code){
$id = base64_decode($id);
$product_id = base64_decode($product_id);
});