欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 5 : MassAssignmentException in Model.php 有大用

Laravel 5 : MassAssignmentException in Model.php

I am getting this error:

MassAssignmentException in Model.php line 448: _token

When I am using create method. Please review code below:

Contacts.php (Model):

class Contacts extends Model{
    protected $table = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];}

ContactsController.php (Controller):

public function store(Request $request){        
    $inputs = $request->all();
    $contacts = Contacts::Create($inputs);
    return redirect()->route('contacts.index');}
shareimprove this questionedited May 12 '16 at 14:55Moppo9,50542940asked Jan 2 '16 at 11:45Sandeep1291112


   MassAssignmentException in Laravel – Kris Roofe Jun 13 at 5:39


4 Answers 正确答案

For the Mass Assignment Exception: you should specify all the fields of the model that you want to be mass-assignable through create or update operations on the property $fillable:

protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];

Besides, the field $table should contain only the model's table name:

protected $table = 'your_table_name';
shareimprove this answeredited Dec 11 at 9:22answered Jan 2 '16 at 11:48Moppo9,50542940

1 Thanks it's workd – Sandeep Jan 2 '16 at 12:011 How could I forget this. Thank you. Works. – pbalazek Mar 25 '16 at 14:53

This might happen in case if you have used the wrongly imported the class. if you are using the User Model.

Wrong Import

// mostly IDE suggestionuse Illuminate\Foundation\Auth\User;

Correct Model Import

use App\User;

i have gone through this. might help someone.

shareimprove this answeranswered Jul 29 '16 at 7:43shakee931,0951120

   Yes it did (: Auto import in IDE may confuse sometimes – Akash Rajput Nov 12 '16 at 14:29

You can all column fillable:

protected $guarded = array();

Add your model.

shareimprove this answeranswered Apr 26 at 10:16Ferhat KOÇER1,108810

If all of the above fails, you can try following. 

Put following after namespace.

use Eloquent;

Put following at the start of your store method.

Eloquent::unguard();

like:

public function store(Request $request){        
   Eloquent::unguard();
   $inputs = $request->all();
   $contacts = Contacts::Create($inputs);
   return redirect()->route('contacts.index');}

This is not recommended though, as this makes things vulnerable to attacks. But if you need a quick fix this might help.

shareimprove this answeranswered Oct 13 at 12:05Joynal Abedin1

来自 https://stackoverflow.com/questions/34565515/laravel-5-massassignmentexception-in-model-php


Laravel First Or New


I seem to be getting the same error when I use UpdateOrNew or FirstOrNew in Laravel, to the best of my knowledge I have implemented the code correctly.

Current Code

    $updateOrCreate = Rating::firstOrNew(
        array(
            'user_id' => Auth::user()->id,
            'video_id' => $_POST['videoId']
            )
    );

    $updateOrCreate->user_id = Auth::user()->id;
    $updateOrCreate->video_id = $_POST['videoId'];
    $updateOrCreate->rating =   $_POST['rating'];

    if($updateOrCreate->save()){
        echo "saved";
    }else{
        echo "failed";
        print_r($_POST);
    };

Error

error: {type:Illuminate\Database\Eloquent\MassAssignmentException, message:user_id,…}file: "/home/celeb/public_html/dev/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php"line: 411message: "user_id"type: "Illuminate\Database\Eloquent\MassAssignmentException"
shareimprove this questionasked Dec 8 '14 at 12:49Brent93752341


   did u check with response on chrome ? – I'm Back Dec 8 '14 at 12:51

2 Answers 正确答案

You need to enable mass assignment in your model as such:

class User extends Eloquent {

    protected $fillable = array('first_name', 'last_name', 'email');}

So any field that can be mass assigned should be in the $fillable variable.

Assigning values without mass assignment:

$user = new User;$user->id = 3;$user->name = "Joe";$user->save();

Assigning values with mass assignment:

$userDetails = array('id' => 3, 'name' => 'Joe');$user = User::create($userDetails);
shareimprove this answeredited Dec 8 '14 at 13:02answered Dec 8 '14 at 12:54Joe1,81111418

1 My struggle here is understanding how assigning it to one entry is mass assignment? – Mikel Bitson Dec 8 '14 at 12:552 Mass assignment is using an array of field values to create a record, rather than doing it one field at a time. – Joe Dec 8 '14 at 12:57   I dont understand this? Sorry but doesn't eloquent map the database? – Brent Dec 8 '14 at 12:58 1 @Brent To prevent any table field to be assigned, by accident or by ill intent, Eloquent only allows assignment on those fields that you have defined in the class property $fillable. – silkfire Dec 8 '14 at 13:021 What I don't understand is why the firstOrNew method should trigger a mass assignment exception since it is merely looking at the database, not attempting to save anything. For example why on earth should this code throw a MAE: $tour = Tour::firstOrNew(array('id' => $this->request['id'])); All it is saying is basically "look and see if there is a row in the database with that ID, if so then return the row, if not, then create a new object with the relevant properties". It isn't saving any data so what is the damn problem...– Inigo Nov 30 '16 at 12:04 

"You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment". [See Laravel Documentation on Eloquent Insert, Update, Delete ] (http://laravel.com/docs/5.0/eloquent#insert-update-delete)

That means, only the create method can protect your codes from mass assignment:

/*$user=*/  User::create(array(            'name'     => 'Max',            'email'    => 'example@example.com'        ));

When using the create method, you specify the model's name which is User from the example above. This model (usually User.php) is the place where you assign the mass assignable variables:

protected $fillable = ['name', 'email'];

shareimprove this answeranswered Aug 18 '15 at 2:17MaXi32174114

1 I want to add comment to someone above instead of replying like this but I need 50 reps. :\ – MaXi32 Aug 18 '15 at 2:20   Just got you to 70 :) – Brent Aug 18 '15 at 8:30 

来自  https://stackoverflow.com/questions/27358423/laravel-first-or-new

 

MassAssignmentException in compiled.php line 10410:name


在新添加数据的时候出现了这个问题,


stackoverflow上是这么解决的:http://stackoverflow.com/questions/34565515/laravel-5-massassignmentexception-in-model-php

然后我就去试了一试,还真的可以;


这个问题是我们没有在模型里面设置批量赋值。


Student.php


  1. <?php  

  2. namespace App;  

  3.   

  4. use Illuminate\Database\Eloquent\Model;  

  5.   

  6. class Student extends Model  

  7. {  

  8.     const SEX_UN = 10;// 未知  

  9.     const SEX_BOY = 20;// 男士  

  10.     const SEX_GRIL = 30;// 女生  

  11.   

  12.     protected $table = 'student';  

  13.   <span style="color:#ff0000;">  protected $fillable = ['name''age' ,'sex'];//添加这句,数组的参数跟你数据库里面表的字段一致</span>  

SutudentController.php


控制器里的的话


  1. <pre name="code" class="html">public function create(Request $request){   </pre><pre name="code" class="html">         

  2.   $data = $request ->input('Student');  

  3.             // 将新增加的数据传进create方法里面  

  4.             if (Student:: create($data)) {  

  5.                 return redirect('student/index') ->with('success' ,'添加成功!');  

  6.   

  7.             } else {  

  8.                 return redirect()->back();  

  9.             }  

  10. }</pre><br>  

  11. <p></p>  

  12. <pre></pre>  

  13. <p></p>  

  14.      



    来自 http://blog.csdn.net/Strenghthen/article/details/60140688



    Laravel Eloquent ORM firstOrNew mass assignment exception

    I'm trying to look up a model in my database based on 2 fields, and if it doesn't exist, create a new model which contains those two values. I'm attempting to use the firstOrNew method to achieve this:

    $store = Store::firstOrNew(array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID));

    However, this code is throwing a MassAssignmentException.

    Is the only way to avoid this exception to assign fillable properties on the class level? According to the documentation, I should be able to assign fillable properties on the instance level, rather than for the entire class, but how would I do that?

    Here's the code for the Store model:

    <?phpuse Illuminate\Database\Eloquent\SoftDeletingTrait;class Store extends Eloquent{
    
            use SoftDeletingTrait;
    
            public function products(){
                    return $this->hasMany('Product');
            }
    
            public function faqs(){
                    return $this->hasMany('ProductFaq');
            }
    
            public function customer_questions(){
                    return $this->hasMany('CustomerQuestion');
            }
    
            public function users(){
                    return $this->hasMany('User');
            }}
    shareimprove this questionedited Aug 28 '14 at 17:03asked Aug 28 '14 at 16:52flyingL1232,46141853

       please add the codes of Store model to your question. – user1922137 Aug 28 '14 at 17:01   I added the code as requested. – flyingL123 Aug 28 '14 at 17:10

    1 Answer 

    正确答案


    fillable() is the method you need:

    $search = array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID);$store = (Store::where($search)->first())
      ?: with(new Store)->fillable(array_keys($search))->fill($search);

    or:

    $store = new Store;$store = ($store->where($search)->first()) ?: $store->fillable(array_keys($search))->fill($search);
    shareimprove this answeranswered Aug 28 '14 at 17:45Jarek Tkaczyk39.6k982107

       The fillable function will only make the attributes fillable for this operation right? – geckob Jun 23 '16 at 1:56   To be precise: for the instance $store, so this and any following operation on it. – Jarek Tkaczyk Jun 23 '16 at 2:13   So, after this operation, whatever we set fillable on Store with this method will be fillable without calling this method again? – geckob Jun 23 '16 at 2:171 fillable is instance property, not static. So it works only for the instance you set in on. It doesn't affect other/new instances of Store model. – Jarek Tkaczyk Jun 23 '16 at 5:45

    普通分类: