Laravel 5.2:创建和编辑功能


Laravel 5.2:create and edit function

我正在使用Laravel 5.2。
userprofile表,是一对一的关系,
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;
}

阅读文档