是否可以加载需要用户 ID 的视图,而无需在 Laravel 5.1 中的 URI 中确定它

Is it possible to load a view that requires a user id, without determining it in the URI in Laravel 5.1

我正在 Laravel 5.1 继续我的冒险。我有一个正在处理的小项目,我正在寻找一种理想的方式来加载用户的 gecko,而无需在 URI 中包含用户 ID。

这是我当前使用的 URI:

Route::get('gecko/{user_id}/{name}', 'GeckoController@show');

如您所见,我在 URI 中保存了用户 ID,然后查询它以找到正确的 gecko。如下图:

public function show($user_id, $name)
{
    $name = str_replace('-', ' ', $name);

    $gecko = Gecko::where(compact('user_id', 'name'))->first();

    return view('gecko.show', compact('gecko'));
}

所以为了让它工作,我会做 project.dev/gecko/1/Zilly - 它工作,但在那里有用户 ID 有点糟糕。我认为拥有用户 ID 很重要,以防多个用户拥有同名 geckos。

非常感谢对此的任何帮助,如果您需要任何额外的代码,请告诉我:)

安迪

如果您想使用用户名而不是 user_id:

路线:

Route::get('gecko/{username}/{geckoname}', 'GeckoController@show');

控制器:

public function show($username, $geckoname) {
    $user_id = User::where('username', $username)->first()->id;
    $geckoname = str_replace('-', ' ', $geckoname);

    $gecko = Gecko::where(compact('user_id', 'geckoname'))->first();
    return view('gecko.show', compact('gecko'));
}

如果用户通过身份验证,您可以使用 Auth::user()->id 并且您应该只添加 gecko id。

例如:

路线:

Route::get('gecko/{gecko_id}', 'GeckoController@show');

控制器:

public function show($id) {    
    $gecko = Gecko::find($id)->where('user_id', Auth::user()->id)->first();
    return view('gecko.show', compact('gecko'));
}

如果您想使用 geckoname:

路线:

Route::get('gecko/{geckoname}', 'GeckoController@show');

控制器:

public function show($geckoname) {   
    $gecko_id= Gecko::where('geckoname',$geckoname)->first()->id; 
    $gecko = Gecko::find($gecko_id)->where('user_id', Auth::user()->id)->first();
    return view('gecko.show', compact('gecko'));
}