Laravel 5.2
我在获取模型ID方面遇到了一些问题:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required',
]);
$data = $request->all();
$page = new Page;
$page->create($data);
dd($page->id);
return redirect()->route('admin.pages.index');
}
$ page-> id返回null ...
我做错了什么?
答案 0 :(得分:1)
如果你想使用laravel的Mass Assign,你应该这样做:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'content' => 'required',
]);
$data = $request->all();
$page = Page::create($data);
dd($page->id);
return redirect()->route('admin.pages.index');
}
然后你就可以得到这样的页面id:
$page_id = $page->id
了解更多信息: https://laravel.com/docs/5.1/eloquent#mass-assignment
并且你的模型类应该是这样的(Fillable):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Page extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title','content'];
}
答案 1 :(得分:0)
在模型中添加质量指定,
ex:protected $ fillable = ['id'];
还没运气?使用此,
$ page = Page :: create($ data);
DD($ PAGE-&GT; ID)