我正在使用Laravel 5.2。
有user
和profile
表,是一对一的关系,
在ProfileController
,用户登录后,
当访问create
功能时,
如果用户的配置文件尚未创建,则返回create
页面,
还
重定向至"edit
功能"。
问题:
如何编写create
函数和edit
函数?
我写了其中的一部分。
1、函数中的参数id
如何编写create
?
2、如何在edit
功能中找到登录用户的个人资料?
配置文件控制器:
public function create()
{
$user = 'Auth::user();
if (!$user->profile) {
return view('profile.create');
}else{
//how to write 'id'
return redirect()->action('ProfileController@edit', ['id' => .......]);
}
}
public function edit()
{
//how to find the profile of the login user?
return view('profile.edit', compact('profile'));
}
你需要这样的东西:
public function create()
{
$user = 'Auth::user();
if(isset($user->profile)) {
return redirect()->action('ProfileController@edit', ['id' => $user->id]);
}
return view('profile.create');
}
// Get the current user
public function edit(App'User $user)
{
if($user->id === 'Auth::user()->id) {
$profile = 'Auth::user()->profile;
return view('profile.edit', compact('profile'));
}
}
$user = 'Auth::user();
和你在public function create()
中一样变量$user
将包含有关当前用户的信息
更多你可以创建一个构造函数方法,如
use Illuminate'Contracts'Auth'Authenticatable;
protected $user;
public function __construct(Authenticatable $user){
// $user is an instance of the authenticated user...
$this->middleware('auth');
$this->user = $user;
}
public function edit(){
$user = $this->user;
}
阅读文档