Laravel API: Timestamps (updated_at, created_at) are null - laravel

I have an API where the user creates the violation information of a certain driver and when I try to input a data into the table using Postman, the created_at column is NULL when it should not be. What could be the problem?
The code below is the lines of code Controller of when storing the data:
public function store(Request $request)
{
$rules=[
'Driver_ID'=>'nullable',
'Truck_ID'=>'nullable',
'Date_happened'=>'nullable',
'Time_happened'=>'nullable',
'offense_level'=>'nullable',
'violation_list'=>'required',
'status'=>'nullable',
'ml_violation'=>'nullable',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response()->json($validator->errors(),400);
}
$data = $request->validate([
'Driver_ID'=>'nullable',
'Truck_ID'=>'nullable',
'Date_happened'=>'nullable',
'Time_happened'=>'nullable',
'offense_level'=>'nullable',
'status'=>'nullable',
'ml_violation'=>'nullable',
]);
// $violationsInformation = Violations::create($data);
$violation_list = json_decode($request->input('violation_list'));
$final_array = [];
foreach($violation_list as $key => $value){
array_push($final_array, [
// 'id'=>$id,
'Driver_ID'=> $request->input('Driver_ID'),
'Truck_ID'=> $request->input('Truck_ID'),
'Date_happened'=> $request->input('Date_happened'),
'Time_happened'=> $request->input('Time_happened'),
'violation_list_id'=> $value->id,
'offense_level'=> $request->input('offense_level'),
'status'=>$request->input('status'),
'ml_violation'=>$request->input('ml_violation'),
]);
}
//$quizRecords = Quiz_Records::create($final_array);
// $violationsInformation = Violations::create($data);
$violationsInformations = DB::table('violation_information')->insert($final_array); // Query Builder approach
return response(['message'=>"Violation's Information successfully created",
'error'=>false,
'error_code'=>200,
'line'=>"line".__LINE__."".basename(__LINE__),
'violationsInformations'=>$violationsInformations],200,[],JSON_NUMERIC_CHECK);
}

In database
You should set type of created_at : timestamp or datetime
And Options is (ON UPDATE)
And default is CURRENT_TIMESTAMP
sql :
ALTER TABLE `your_table`
CHANGE `created_at` `created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP;

Instead of ->insert method use create method. The created_at and updated_at fields are updated by Eloquent (If using $table->timestamps() they are default NULL).

Related

get latest record against foreign key and check whether its specific column has value NULL or not

Hi I am working on a project Laravel where I need to update record in database by fetching last(latest) record against foreign key, The scenario is fetch latest record(row) and if its specific column (amendments_to) has NULL value update it with some string else insert a new record. Below is my code what it does is always updates last row only no matter what the value in amendments_to column is.
OrderResponse::where('send_id', $id)
->orderBy('id', 'desc')
->take(1)
->update(['amendments_to' => $request->comment]);
If you only are doing it with a single row at a time, i would simply do a more Eloquent approach. Laravel has a helper for latest() query.
$orderResponse = OrderResponse::where('send_id', $id)
->latest()
->first();
if (!$orderResponse->amendments_to) {
$orderResponse->amendments_to = $request->comment;
$orderResponse->save();
} else {
$newOrderResponse = new OrderResponse([
'amendments_to' => $request->comment,
'send_id' => $id,
// other fields
]);
$newOrderResponse->save();
}

Set the value in the model so that when inserting or updating automatically added to the database in laravel?

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
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');
});
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.
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

Created at timestamp is null when retrieve

I am saving data using sensor where data is coming like this
$input = $request["date"].' '.$request["time"];
$newDate= DateTime::createFromFormat('d/m/Y H:i:s',$input);
$created_date = $newDate->format('Y-m-d H:i:s'); // for example
try{
$SensorData = SensorData::create([
'sensor_id' => $request['sensor']['id'],
'created_at' => "".$created_date."",
]);
$sensor_data=SensorData::join('sensors','sensors.id','=','sensor_id')->orderBy('sensor_data.created_at','DESC')->get();
its saving datetime in database as 2020-05-04 01:10:12 but when retrieve value it shows null
Using DB clause has solved the problem
$sensor_data = DB::table('sensors')
->join('sensor_data', 'sensors.id', '=', 'sensor_data.sensor_id')
->get();

Laravel not updating null values to column

Migration
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('username',50)->unique();
$table->date('start_date');
$table->date('end_date')->nullable();
$table->timestamps();
});
Here start_date set as column type date and nullable
When running Insert function like below its inserting null values
$insert = [
'username' =>strtoupper(request('username')),
'password' =>Hash::make(request('password')),
'start_date' =>date('Y-m-d',strtotime(request('start_date'))),
];
if(request()->filled('end_date')){
$insert['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}
User::create($insert);
When Updating the same row left blank as end_date input,
$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
$update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
$update['end_date'] = 'NULL';
}
$user->update($update);
In Table, it comes like below
How can I make it NULL like insert function in update?
My strict mode is false now, If I make it true it will throw an exception of invalid data for the end_date column.
Try replacing
}else{
$update['end_date'] = 'NULL';
}
with
}else{
$update['end_date'] = null;
}
'NULL' is a string whereas null is truly null.
you have 2 solution for this problem:
1.
$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
$update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
$update['end_date'] = '".date('00:00:00')."';
}
$user->update($update);
2.
you have to set default in mysql database on end date field
First set table field to nullable()
Second set table field DEFAULT to NULL
Third:
$model->field = null;

How to select field in another table join by eager loading in Laravel

I got category_to_news and news_main table
category_to_news
news_id int
name varchar
title timestamp
news_main
id int
title varchar
image varchar
created_at timestamp
how to return by news_main's field and category_news's field ? I've tried this method and it's not work
$posts = Categorytonews::with(array(
'Newsmain' => function($query)
{
$query->orderBy('id', 'DESC')->select(array('title', 'id', 'created_at', 'image'));
}
))
->get( );
You need join for this because with() runs another query, so ordering there won't do the job:
$posts = Categorytonews::with('Newsmain') // get all fields from Newsmain
->join('news_main', 'category_to_news.news_id', '=', 'news_main.id') // join for ordering
->orderBy('news_main.id','desc') // order by joined field
->get('category_to_news.*'); // select only main table, you don't need joined fields
// on Categorytonews model - they will be loaded by with()
$posts = Categorytonews::with(array('Newsmain' => function($query)
{
$query->select(array('title', 'id', 'created_at', 'image'))->orderBy('id', 'DESC');
}))->get();

Resources