【发布时间】:2020-01-23 00:33:19
【问题描述】:
在我的应用程序中,我有一个用户表和一个配置文件表。当用户访问他们的仪表板时,他们应该能够单击一个链接来查看他们的个人资料页面。这是链接:
<a href="{{ route('profiles.show',$profiles->id)}}">link to your profile page</a>
但是,我收到错误消息:Route [profiles.show] not defined。
我是新手,不清楚如何将注册用户与他/她的个人资料页面相关联。所有用户在注册时都应该有一个个人资料页面。
不胜感激!这是我目前所拥有的:
个人资料页面的链接
<a href="{{ route('profiles.show',$profiles->id)}}">link to your profile page</a>
ProfilesController.php
namespace App\Http\Controllers;
use App\Profile;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function show($id)
{
$profile = Profile::find($id);
return view('profiles.show', compact('profile'));
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
routes/web.php
Route::get('pages/profiles', 'ProfilesController@show');
profiles.blade.php
这只是一个非常简单的页面。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>{{ $user->user_id }}</h1>
<p>{{ $user->about_me }}</p>
</body>
</html>
解决方案
我找到了一个简单的解决方案,我想在此处发布它以帮助其他可能在创建用户个人资料页面时遇到困难的人。下面假设您的数据库中已经有一个用户表,现在您想要创建一个配置文件表并将用户 ID 连接到他们的配置文件页面。 添加 Laravel 用户配置文件
我是the video,对我有帮助。
创建表
php artisan make:migration create_profiles_table
这会创建一个迁移文件:
2019_09_22_213316_create_profiles_table
打开迁移文件并添加您需要的额外列:
$table->integer('user_id')->unsigned()->nullable();
$table->string('about_me')->nullable();
将这些迁移到数据库
php artisan migrate
现在我们已经对数据库进行了排序,我们需要创建一个控制器来控制我们的 php 功能。
ProfilesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}
routes/web.php
Route::get('dashboard/profile', 'ProfilesController@show');
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
将此添加到 User.php
public function profile()
{
return $this->hasOne('Profile');
}
profile.blade.php
创建您想要的任何设计。如果你想拉入用户名,包括{{ Auth::user()->name }}
【问题讨论】:
标签: laravel