laravel5.4 表单提交

前提添加路由: Route::post('/page', 'PostController@store');
首先需要在blade模板的添加代码:
为了防止csrf攻击,需要添加一句话:
<input name="_tabken" value="{{csrf_token()}}" type="hidden"> 或者 {{csrf_field()}} 都可以!
<form action= "/page" method= "POST" >
{{csrf_field()}}
<div class= "form-group" >
<label> 标题 </label>
<input name= "title" type= "text" class= "form-control" placeholder= " 这里是标题 " >
</div>
<div class= "form-group" >
<label> 内容 </label>
<textarea id= "content" style= " height:400 px ;max-height:500 px ; " name= "content" class= "form-control" placeholder= " 这里是内容 " ></textarea>
</div>
<button type= "submit" class= "btn btn-default" > 提交 </button>
</form>
<br>
</div>
接着控制器中需要:
public function store()
{
// 方法一:
/*$post = new Post();
$post->title = request('title');
$post->content = request('content');
$post->save();*/

// 方法二:
/*$params = ['title' => request('title'), 'content' => request('content')];
Post::create($params);*/

// 方法三:用数组传递需要对 model 进行设置
$res = Post::create(request(['title', 'content']));
return redirect('page');
}
最后需要对model进行设置:选择一种就可以
class Post extends Model
{
protected $guarded = []; // 不允许注入的字段 : 空数组表示允许所有
// protected $fillable = ['title', 'content']; // 可以注入的数据字段
}

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/79170961