我正在努力学习Laravel,并在将一行插入数据库后努力学习如何返回id。
这是我当前的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());
}
}
我已经尝试添加$form->id,但它不起作用。我得到一个未定义的属性:NotesCreation::$id
这是我的笔记创建模型:
public function save()
{
$success = false;
if ($this->isValid()) {
$this->user->notes()->save($this->notes);
$success = (bool) $this->notes;
}
return $success;
}
我做错了什么?我非常感谢任何帮助!谢谢
使用一种简单的方法获取最后插入的id。
$leadmodel = new Lead(); //mhy model name
$leadmodel->name = 'name';
$leadmodel->save();
$lead_id = $leadmodel->id; //last inserted id
echo $lead_id ;
您的->notes()->save()方法必须返回id:
$success = $this->user->notes()->save($this->notes);
return $success;
您可以在中阅读有关如何返回最后一个未登录id的信息:http://laravel.com/docs/4.2/eloquent#insert-更新删除或http://laravel.com/docs/4.2/queries#inserts
如果您正在使用创建函数
$customer_id = Customer::create(array(
'name' => $data->customer->name,
'phone' => $data->customer->phone,
'address' => $data->customer->address
))->id;
dd($customer_id);
如果您正在使用保存,请使用此
$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);