首页 > 解决方案 > Laravel 7在用户名前添加@符号

问题描述

我正在使用 Laravel 7 进行简单项目,我想在我的项目中激活一个简单的技巧我想在用户名之前添加 @ 符号,如下例所示:http://app.test/@jhondoe

活生生的例子:Laracasts

这是我的用户资料路线:

Route::get('profile/{slug}/{id}', 'Backend\UserController@UserProfile')->name('profile');

这是用户配置文件控制器:

<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
   /**
     * Show the User Profile.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function UserProfile($slug, $id)
    {
        return view('profile');
    }
}

这是一个访问用户配置文件的简单按钮:

<a href="{{ URL('profile') }}/{{ Auth::user()->slug }}/{{ Auth::user()->id }}" class="btn btn-info">My Profile</a>

标签: phplaravel-7

解决方案


创建新路线

Route::get('@{user:slug}', 'Backend\UserController@UserProfile')->name('profile');

现在在控制器中接收用户

    public function UserProfile(User $user)
    {
        return view('profile',compact($user));
    }

然后在视图中显示用户的个人资料,访问$user->属性

这假设您在 User 模型上有一个 slug 列,并且该列在创建时已被验证为唯一


推荐阅读