【问题标题】:getting user profile using a slug使用 slug 获取用户配置文件
【发布时间】:2018-02-10 20:21:00
【问题描述】:

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

地址栏应该是

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

相反,它总是读取

.app:8000/profile/firstuser .

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

路线

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());

    }
}

【问题讨论】:

  • 你为什么要使用ProfileComposer
  • 这个$view-&gt;with('profile', Auth::user()-&gt;profile-&gt;first()) 应该是$view-&gt;with('profile', Auth::user()-&gt;profile)$view-&gt;with('profile', Auth::user()-&gt;username),这取决于你想从哪个列中选择他们的名字。
  • Stanley,就是这么简单,只需取出 ->first() 即可。谢谢一声。也许回复作为答案?

标签: laravel-5 illuminate-container


【解决方案1】:

您可以在RouteServiceProvider中自定义路由模型绑定的查询逻辑:

public function boot()
{
    parent::boot();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 2019-04-07
    • 2015-02-09
    • 1970-01-01
    • 2017-04-19
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多