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.
CodePudding user response:
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
CodePudding user response:
You should use create
instead of insert
.
User::create($data);
CodePudding user response:
Use create()
method instead of insert()
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::create($data);
}