Laravel 5 Array with saving the key in the model

Have an array that has a key and value . Key names are the same database column names.

There are more than 50 keys in the index.

  • So, it is impossible to save data one by one, for example

    $user = new User; $user->name = 'John'; .......... ....... .......so on $user->save(); 

Array example:

  Array
 (
     [name] => 'Amit',
     [age] => 25,
     [field1] => 'val1',
     ....
   [field33] => 'how',
 ....
    [field54] => 'sumit'     
 )

Now, my question is how can I save data in a model using the simplest process.

Information:

  • Using laravel 5

Try:

 $Plan=new Plans; $Plan->fill( $array); $Plan->save(); 

Note: I know that padding does not work, because it is not defined with this model's populated variable

+5
source share
2 answers

The Eloquent model encapsulated the attributes of an object. Thus, you can only modify or set them using the set ( $model->attribute ) or fill(array $attributes) methods. All Eloquent methods that assign mass to attributes use the fill() method.

So, there are two ways to insert new Eloquent-based models with an array in the database that uses the fill() method and one that doesn't work.

Method 1: Mass Assignment

Add the attribute protected $fillable = [ 'column_a', 'column_b', .. ]; to your model. Then you can use bulk assignment as follows.

 $Plan = new Plans; $Plan->fill( $array ); $Plan->save(); 

Or you can use:

 $plan = Plans::create( $array ); 

Method 2: QueryBuilder :: insert (array)

If you don't have boot methods registered with creating and created (DB will not run them), you can also use QueryBuilder to insert rows into the database.

 // insert one plan DB::table('plans')->insert([ $array ]); $plan = Plans::find( DB::getPdo()->lastInsertId() ); // insert multiple plans in one query $plans = [ $plan_a_arr, $plan_b_arr, .. ]; DB::table('plans')->insert( $plans ); 
+2
source

I don’t understand why you don’t want to define the database columns / arrays in the $fillable attribute of your model, since this is just a one-time task, and then you can do it simply:

 $plan = Plans::create( $array ); 

Another way, if you have all the data in an associative array with the keys corresponding to the columns of the DB table that you are doing, use the foreach loop:

 $plan = new Plans; foreach( $array as $key => $value ) { $plan->$key = $value; } $plan->save(); 
+2
source

Source: https://habr.com/ru/post/1238922/


All Articles