使用slug获取用户配置文件

时间:2018-02-10 20:21:00

标签: laravel-5 illuminate-container

我正在尝试使用独特的slug检索用户个人资料。用户登录后,我只能获取db中记录的第一个配置文件而不是登录用户,我不知道为什么?如果我没有登录,我仍然希望能够查看个人资料。

地址栏应为

.app:8000 / profile / signedinsuer或所选用户

而是始终读取

.app:8000 / profile / firstuser。

我可以手动更改地址栏,其余的工作正常,我得到正确的视图等。我只是没有得到正确的slu ..

路线

Route::group(['prefix' => '/profile'], function () {
    Route::get('/{profile}', 'Profile\ProfileController@index')->name('profile.index');

控制器

class ProfileController extends Controller
{
    public function index(Profile $profile)
    {
        return view('overview.profile.index', [
            'profile' => $profile,
        ]);
    }
}

从刀片

<li>
    <a href="{{ route('profile.index', [$profile]) }}">Profile</a>
</li>

作曲

class ProfileComposer
{
    public function compose(View $view)
    {
        if (!Auth::check()) {
            return;
        }

        $view->with('profile', Auth::user()->profile->first());

    }
}

1 个答案:

答案 0 :(得分:0)

您可以在RouteServiceProvider

中自定义路径模型绑定的查询逻辑
public function boot()
{
    parent::boot();

    Route::bind('profile', function ($value) {
        return App\User::where('profile', $value)->first() ?? abort(404);
    });
}