Laravel保存时如何获取当前模型的id

Luc*_*ois 5 php laravel laravel-5

我正在 Laravel 5 应用程序中工作。我尝试保存项目评论,但不知道如何获取$comment->project_id值。

这是我的简化控制器

public function store( CommentsFormRequest $request )
{
    $comment = new Note;
    $comment->message              = Input::get('message');
    $comment->project_id           = $note->project->id;
    $comment->user_id              = Auth::id();
    $comment->save();

    return Redirect::back();
}
Run Code Online (Sandbox Code Playgroud)

这是我的简化表格

  {!! Form::open(array('route' => 'notes.store')) !!}

    {!! Form::textarea('message', '', array('placeholder'=>'Message')) !!}

  {!! Form::submit('Ajouter la note') !!}
  {!! Form::close() !!}
Run Code Online (Sandbox Code Playgroud)

当我尝试保存时,出现以下错误:

Trying to get property of non-object
Run Code Online (Sandbox Code Playgroud)

我猜这是因为它试图获取新对象的 sollicitation_id 为空。我应该如何获取当前的project_id值?

更新

结论:我使用了隐藏字段并遵循了 @tommy 的建议。我的控制器现在使用

$note->project_id  = $request->input('project_id');
Run Code Online (Sandbox Code Playgroud)

我的隐藏字段是

{!! Form::hidden('project_id', $project->id ) !!}
Run Code Online (Sandbox Code Playgroud)

shr*_*gon 6

仅当表主列名称为“id”时:

$model->id;
Run Code Online (Sandbox Code Playgroud)

无论主列名称如何:

$model->getKey();
Run Code Online (Sandbox Code Playgroud)


tom*_*mmy 2

在 store 方法中,您尝试获取project变量 的属性$note,但该属性不存在。您应该通过将项目 ID 添加到路由或将隐藏字段添加project_id到表单来将项目 ID 传递到 store 方法。

然后,您的 store 方法应该如下所示:

public function store($project_id, CommentsFormRequest $request )
{
    $project = Project::find($project_id); // $project_id is transmitted over the URL

    $comment = new Note; // I'd alias Note as 'Comment', or rename '$comment' to '$note' because this can be confusing in the future
    $comment->project_id = $project->id;
    $comment->save();

    return Redirect::back();
}
Run Code Online (Sandbox Code Playgroud)

如果您想将带有项目 ID 的隐藏字段添加到表单中,您可以通过调用来访问其值$request->input('project_id');