【问题标题】:Laravel 5.2:create and edit functionLaravel 5.2:创建和编辑功能
【发布时间】:2016-02-24 23:04:25
【问题描述】:

我正在使用 Laravel 5.2 ..
有一个user 和一个profile 表,它们之间是一对一的关系,
ProfileController,
用户登录后,
当访问create函数时,
如果用户的个人资料尚未创建,返回create页面,
否则,
重定向到edit 函数。

问题:
create函数和edit函数怎么写?
我写了其中的一部分。
1、create函数中的参数id怎么写?
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'));
    }

【问题讨论】:

  • 我会改为在 User::create() 上创建相应的个人资料记录:laravel.com/docs/master/eloquent#events
  • @MartinBean 没看懂,举个例子更好。
  • @sunshine 我指给你看文档,里面有例子。

标签: php laravel


【解决方案1】:

你需要这样的东西:

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'));
    }
}

【讨论】:

  • edit(App\User $user) 你不传递一个实例你只传递一个 ID ['id' => $user->id]
  • @Froxz 这是在 5.2 中使用路由模型绑定。
  • 好的)我还在用 5.1))
  • 有错误:Missing required parameters for [Route: api.profile.edit] [URI: api/profile/{profile}/edit].
  • 是的,您需要在 url 中传递用户 ID。
【解决方案2】:
$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;
}

阅读DOCS

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2023-03-31
    • 2016-09-15
    • 2016-07-03
    • 2023-02-15
    • 2017-10-09
    • 1970-01-01
    • 2016-11-04
    • 2016-08-04
    相关资源
    最近更新 更多