Home > Net >  Set the value in the model so that when inserting or updating automatically added to the database in
Set the value in the model so that when inserting or updating automatically added to the database in

Time:11-03

In the database I have columns: id, name, order, createdAt, updatedAt, createdBy, updateBy .

In controller : PostController.php

public function store(Request $request)
{
   $req = Validator::make($request->all(), [
       'name' => 'required',
       'order' => 'required',
   ]);
   if ($req->fails()) {
      return response()->json(['error' => $req->errors()], 400);
   }
   $data = $request->all(); // name and order
   Post::insert($item);
}

I want when I add data. Then createAt column and createBy column will be added. Instead of setting date('Y-m-d H:i:s) and $request->user()->id in controller, Then I want it to be placed in model, when i insert createAt and createBy columns are added. If it's update then I want the updatedAt and updatedBy columns to be added

CodePudding user response:

You can add both createdAt and updatedAt in your migration file. That will insert the current timestamp while inserting values into the table without adding them into the controller. Please try like this while adding migration

Schema::create('table_name', function (Blueprint $table) {
   $table->timestamp('createdAt');
   $table->timestamp('updatedAt');
});

CodePudding user response:

Instead of doing POST::insert($data); you could create/update a model more explicitly.

To add a new Post with only createdAt and createdBy you could do something like this:

$post = new Post;
$post->createdAt = $dateTime;
$post->createdBy = $userId;
$post->save();

Of course you can set any other attributes you are wanting to include before you save. And your updatedAt and updatedBy columns will have to be nullable in the database so that you don't get an error when you try to insert a record without including them.

Also as a note, Laravel has a feature that includes created_at and updated_at columns if you have: $table->timestamps(); included in your table's migration file. These fields will get automatically updated whenever a database entry is created/updated.

CodePudding user response:

in your migration, you can just use the timestamps, it by default creates created_at and updated_at, and when you update an entry, Eloquent will update the value automatically for you, as for the created_by and updated_by, you can create them as well in migration, then setup an observer to set the values on create/update

ref: https://laravel.com/docs/8.x/eloquent#observers

  • Related