Search code examples
phpmysqllaravellaravel-4

Return primary id after Save in Laravel


I am trying to learn Laravel and struggling on how to return an id after I've inserted a row into the database.

Here is my current NotesController:

    public function store()
{
    $form = new NotesCreation($this->currentUser(), $this->params());
    if ($form->save()) {
        return Redirect::route('notes.edit', WHERE ID NEEDS TO GO)
            ->withSuccess('Note added successfully');
    } else {
        $this->view('create')
            ->withErrors($form->getErrors());
    }
}

I have tried to add $form->id, but it does not work. I get an Undefined property: NotesCreation::$id

This is my NotesCreation model:

    public function save()
{
    $success = false;

    if ($this->isValid()) {
        $this->user->notes()->save($this->notes);

        $success = (bool) $this->notes;
    }

    return $success;
}

What am I doing wrong? I greatly appreciate any help! Thanks!


Solution

  • Your ->notes()->save() method must return the id:

    $success = $this->user->notes()->save($this->notes);
    return $success;
    

    You can read about how to return last intested id in: http://laravel.com/docs/4.2/eloquent#insert-update-delete or http://laravel.com/docs/4.2/queries#inserts