PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] created_at and updated_at don't update automatically on insert in laravel

 January 19, 2022     laravel     No comments   

Issue

I use laravel 8 :

public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('created_by')->nullable();
            $table->string('created_by_user')->nullable();
            $table->timestamps();
        });
    }

Models:

<?php

namespace App\Models\Backend\MySQL;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
}

In controller :

use App\Models\User;

public function store(Request $request) {
    $data = [
        'name' => !empty($request->name) ? $request->name : 'Jony',
        'created_by'    => auth()->user()->id,
        'created_by_user'    => auth()->user()->name,
    ];
    User::insert($data);
}

I have successfully inserted. But the problem is that my created_by and updated_by columns are not updating automatically. Is there any way to solve this problem. In the user model I also don't set protected $timestamps = false but it doesn't work. Thank you.


Solution

insert method is not for eloquent models and doesn't update created_at and updated_at. you should use create method instead.

create method sets created_at and updated_at automatically

see this answer here

https://stackoverflow.com/a/58075757/7689224



Answered By - ehsan asarzadeh
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing