Lucien Dubois Lucien Dubois - 2 months ago 5x
PHP Question

How to get the id of the current model in Laravel when saving

I am working in a Laravel 5 application. I try to save a comment for a projet and I don't know how to get the $comment->project_id value.

Here is my simplified controller

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

return Redirect::back();

and here is my simplified form

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

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

{!! Form::submit('Ajouter la note') !!}
{!! Form::close() !!}

When I try to save, I get this error:

Trying to get property of non-object

I guess it's because it tries to get the sollicitation_id of the new object wich is null. How should I get the current project_id value?


Conclusion: I used an hidden field and followed @tommy 's recommendation.
My controller now uses

$note->project_id = $request->input('project_id');

and my hidden field is

{!! Form::hidden('project_id', $project->id ) !!}


In the store method, you try to get the property project of the variable $note, which does not exist. You should pass the project ID to the store method by either adding it to the route or adding a hidden field project_id to your form.

Then, your store method should look something like this:

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;

    return Redirect::back();

If you want to add a hidden field with the project ID to the form, you can access its value by calling $request->input('project_id');