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();
Related
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).
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();
}
I have a expiry_date (type=date) column in my table
$currentDate = date('Y-m-d');
$Data = Post::whereDate('expiry_date','<=',$currentDate)->where(['status' => 'active'])->orWhere(['p_id' => 3])->select('id','title','status','p_id','expiry_date')->orderBy('id', 'DESC')->get();
i want to filter data if current date is greater than expiry date then those record should not be shown but in my scenario i'm still getting record.
Any solution Thanks.
You must group orWhere clause in closure. Grouping in closure is like () in real query.
$Data = Post::whereDate('expiry_date','<=',$currentDate)
->where(function($query){
return $query
->where(['status' => 'active'])
->orWhere(['p_id' => 3]);
})
->select('id','title','status','p_id','expiry_date')
->orderBy('id', 'DESC')
->get();
But, because I don't know your project - i may wrong with grouping.
This raw SQL query is returning the expected result on my SQL console. Would you please help me to transform it into a Laravel Eloquent query?
SELECT * FROM `my_services`
WHERE `user_id` = 1 and `financial_year` = '2021-2022'
AND (service_type = 'Return' OR service_type = 'Correction Return')
ORDER BY id DESC LIMIT 1,1;
I have tried to implement it like the following.
MyService::where([
'user_id' => $user->id,
'financial_year' => $request->financial_year,
'financial_year' => '2021-2022'
])
->orWhere(['service_type' => 'Return'])
->orWhere(['service_type' => 'Correction Return'])
->orderBy("id", "desc")
->offset(1)
->limit(1)
->get();
Try this query -
MyService::where('user_id', 1)->where('financial_year', '2021-2022')->where(function($q) {
$q->where('service_type', 'Return')->orWhere('service_type', 'Correction Return');
})->limit(1)->offset(1)->orderBy('id', 'DESC')->get();
From: https://laravel.com/docs/8.x/queries#limit-and-offset
Use ->skip(1) or ->offset(1) for offset
Use ->take(1) or ->limit(1) to limit count of returned results
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();