Reputation: 57
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!
Upvotes: 2
Views: 1453
Reputation: 43
If you are using create function
$customer_id = Customer::create(array(
'name' => $data->customer->name,
'phone' => $data->customer->phone,
'address' => $data->customer->address
))->id;
dd($customer_id);
if you are using save than use this
$customer = new Customer();
$customer->name = $data->customer->name;
$customer->phone = $data->customer->phone;
$customer->address = $data->customer->address;
$customer->save();
$customer_id = $customer->id;
dd($customer_id);
Upvotes: 0
Reputation: 941
Use a simple way to get the last inserted id.
$leadmodel = new Lead(); //mhy model name
$leadmodel->name = 'name';
$leadmodel->save();
$lead_id = $leadmodel->id; //last inserted id
echo $lead_id ;
Upvotes: 1
Reputation: 51
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
Upvotes: 0