Creating and Update Laravel Eloquent

Creating and Update Laravel Eloquent

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link

laravel eloquent update or create

You have error in your syntax:

'number_of_rows', $mainRows

I assume should be:

'number_of_rows' => $mainRows
DynamicTable::updateOrCreate([
'component_id' => $getComponentMainId->id,
'generated_workflow_id' => $created_generated_form['id'],
'form_id'=> $form_id,
],[
'number_of_rows' => $mainRows,
'row_indexes' => $indexes
]);

Laravel Eloquent update related records

Normally this type of update process is a bit lengthy but efficient and optimal as compared to delete and insert hack, there are many benefits of this approach

  • Primary key of a records remains same as compared to other approach which creates a new record and assign a new primary key
  • You can track update_at timestamp which will change on every update while in case of delete/insert the created_at and updated_at will have same values forever
  • No unnecessary auto increments added on database side, like sale 1 has 3 records with id 1,2,3 and on update without changing any data the records will be deleted and inserted again and their ids will be 4,5,6 and next auto increment will be set to 7

Lets say in database you already have 2 rows for sale 1

______________________________________________
| id | sales_id | item_id | price | quantity |
----------------------------------------------
| 1 | 1 | 1 | 20 | 5 |
----------------------------------------------
| 2 | 1 | 2 | 10 | 5 |
----------------------------------------------

Let say you have following collection to perform update for sale 1

$collection = collect([
[
"id"=> null,
"sales_id"=>1,
"item_id"=> 1,
"price"=>10,
"quantity"=> 0
],
[
"id"=> 1,
"sales_id"=>1,
"item_id"=> 1,
"price"=>10,
"quantity"=> 0
]
]);

Now if we compare database results and the requested update collection we can see the there is

  • one insert for first item in collection because id is null
  • one update for second item in collection because id 1 exists in database
  • one delete because in requested collection there is no item with id 2 so that needs to be deleted

To perform above updates first we need to collect all items where id is null so we will add these records in database

$addItems = $collection->whereNull('id'); 
if($addItems->count() > 0){
SaleItem::insert($addItems);
}

For update we need to collect items where id is present and these records will be updated in database as

$updateItems = $collection->whereNotNull('id');
foreach($updateItems as $key => $updateItem) {
SaleItem::where('id', $updateItem->id)->update($updateItem);
}

Or we can use upserts for first and second step as

SaleItem::upsert($updateItems, ['id']);

For delete we can get all ids from collection and perform delete operation on rows that do not match these ids as

$deleteItems = $updateItems->pluck('id');
SaleItem::whereNotIn('id', $deleteItems)->delete();

Laravel: how to create a function After or Before save|update

Inside your model, you can add a boot() method which will allow you to manage these events.

For example, having User.php model:

class User extends Model 
{

public static function boot()
{
parent::boot();

self::creating(function($model){
// ... code here
});

self::created(function($model){
// ... code here
});

self::updating(function($model){
// ... code here
});

self::updated(function($model){
// ... code here
});

self::deleting(function($model){
// ... code here
});

self::deleted(function($model){
// ... code here
});
}

}

You can review all available events over here: https://laravel.com/docs/5.2/eloquent#events

Laravel Eloquent - bulk update with whereIn array

Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.

the implementation is simple, add a simple code to the Model class, then add:

User::massUpdate(
values: [
['username' => 'iksaku', 'name' => 'Jorge González'],
['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
],
uniqueBy: 'username'
);

while uniqueBy is the key for the row, and add other columns values to change them dynamically.

Laravel eloquent update column value by adding new value

"Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries."

Laravel 5.5 Docs - Eloquent - Retrieving Models

You can use Eloquent to use any of the Query Builder methods or any Eloquent specific methods.

Laravel: Form add is ok . But when I want to update it gives me error

You will require updated_at column in your Database, add this in migration :
$table->timestamps();
then re run the migration



Related Topics



Leave a reply



Submit