2

I am new to Laravel. I am looking for a way to insert a value to specific field such as created_at automatically whenever the row is inserted to the DB table.

I found out that only Eloquent way which uses some Model->save() inserts timestamp to desired field.

But I want to be able to insert a value even when I use QueryBuilder. Is there any way to do so?

I have looked at this post: Query builder not inserting timestamps

Any advice would be appreciated.

Thank you in advance

smchae
  • 1,035
  • 3
  • 17
  • 39

2 Answers2

1

You've said before you're using Model::insertGetId(), but the thing is this method is not using Eloquent. It's a Query Builder method. So, use create() instead:

$object = Model::create($data);
$id = $object->id;

If you still want to use insertGetId(), you'll need to add created_at timestamp manually:

$data['created_at'] = now();
Model::insertGetId($data);

Or you could set CURRENT_TIMESTAMP as a default for timestamp column, but it's so much better to just use Eloquent to handle this.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
-1

You can make a new helper methods in helpers.php Something like this:

public function queryBuilderInsert($table, $data, $deleted_at = false)
    {
        $data['created_at'] = \Carbon::now();
        $data['updated_at'] = \Carbon::now();
        $deleted_at ? $data['deleted_at'] = null :;

        \DB::table($table)->insert($data);
    }
public function queryBuilderUpdate($builder, $data)
    {
        $data['updated_at'] = \Carbon::now();
        $builder->update($data);
    }

And then you can build your queries like this:

For insert use queryBuilderInsert method

$example_data = [
    'name' => 'Name',
    'email'=> 'Email'
];
queryBuilderInsert('users',$example_data);

If you're using soft deletes on your table you can use the third parameter of queryBuilderInsert

queryBuilderInsert('users',$example_data, true);

For update, you can make your query and then call queryBuilderUpdate method

$example_update_data = [
    'name' => 'Name',
    'email'=> 'Email'
];
$builder = \DB::table('users')->where('id',1);
queryBuilderUpdate($builder,$example_update_data);

It will set updated_at date and make update