本文實(shí)例講述了laravel5.1框架下的批量賦值實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
官方中文文檔在這里:
http://laravel-china.org/docs/5.1/eloquent#%E6%89%B9%E9%87%8F%E8%B5%8B%E5%80%BC
我先來說明一下一個(gè)場(chǎng)景:
你想要往數(shù)據(jù)庫(kù)中存評(píng)論,在控制器的代碼如下:
$comment->comment_id= $id;
$comment->title = $name;
$comment->url = $url;
$comment->introduction = $profile;
if ($comment->save()) {
return redirect('admin/comment');
} else {
return redirect()->back()->withInput()->withErrors('保存失??!')
設(shè)想一下如果這個(gè)評(píng)論表的字段有很多,豈不是要一個(gè)字段一個(gè)字段的存儲(chǔ),代碼量太高。laravel框架提供了一個(gè)叫做批量賦值的功能:
控制器代碼如下:
public function store(Request $request)
{
if (Comment::create($request->all())) {
return redirect()->back();
} else {
return redirect()->back()->withInput()->withErrors('評(píng)論發(fā)表失敗!');
}
}
對(duì)應(yīng)的App\models中的Comment類:
?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['nickname', 'email', 'website', 'content','article_id'];
}
protected $fillable= ['nickname','email','website','content','article_id'];
這一行就表示控制器中得到的數(shù)據(jù)全部存入相應(yīng)字段,是不是很簡(jiǎn)單方便?
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Laravel 批量更新多條數(shù)據(jù)的示例
- laravel實(shí)現(xiàn)批量更新多條記錄的方法示例
- Laravel中批量賦值Mass-Assignment的真正含義詳解
- Laravel框架學(xué)習(xí)筆記之批量更新數(shù)據(jù)功能
- Laravel框架實(shí)現(xiàn)的批量刪除功能示例
- laravel批量生成假數(shù)據(jù)的方法
- Laravel向公共模板賦值方法總結(jié)
- Laravel 實(shí)現(xiàn)Controller向blade前臺(tái)模板賦值的四種方式小結(jié)
- Laravel5.1數(shù)據(jù)庫(kù)連接、創(chuàng)建數(shù)據(jù)庫(kù)、創(chuàng)建model及創(chuàng)建控制器的方法
- Laravel5.1框架注冊(cè)中間件的三種場(chǎng)景詳解
- laravel5.1框架model類查詢的實(shí)現(xiàn)方法