Home > Blockchain >  Laravel insert created and updated null
Laravel insert created and updated null

Time:12-09

Hello i'm saving multi records with insert but it is not adding created_at and updated_at it's null

public function store(Request $request)
{
    CategoryUser::insert(
        collect($request->userId)
            ->crossJoin($request->categoryId)
            ->map(
                fn ($pair) => ['user_id' => $pair[0], 'category_id' => $pair[1]]
            )
            ->all()
    );
    return redirect()->back();
}

so how can i add created and update time() or something like this?

CodePudding user response:

The ::insert() method doesn't automatically apply created_at or updated_at. You have a couple options:

  1. Loop and use the create() method:
$data = collect($request->input('userId'))
  ->crossJoin($request->input('categoryId'));

foreach ($data as $categoryUser) {
  CategoryUser::create(
    ['user_id' => $categoryUser[0], 'category_id' => $categoryUser[1]]
  );
}
  1. Manually map them:
CategoryUser::insert(
  collect($request->input('userId'))
  ->crossJoin($request->input('categoryId'))
  ->map(fn ($pair) => [
    'user_id' => $pair[0],
    'category_id' => $pair[1],
    'created_at' => Carbon::now(),
    'updated_at' => Carbon::now()
  ])
  ->all()
);

(Don't forget to add use Carbon\Carbon; to the top of your Class)

CodePudding user response:

Alternatively you can add migration so that it auto store current time. in migration change field. $table->date('app_date')->default(DB::raw('NOW()'))

  • Related