Laravel show different date from my database - php

I have a problem in my project. When I store value in my database it works perfectly fine. But when I want to show the value it gives me an undefined date that is not stored in my database.
Here In my database the created_at field value is 2017-02-18 16:23:37. But When I want to show this in my view page it gives me this
It gives me the value of 2017-02-02 09:19:40. I don't understand whats wrong.
I am only showing the created_at field. Please help me
My controller is
public function showApplication() {
$dataList = ApplicationModelOL::leftJoin('certificate', 'application.application_certificate_id', 'certificate.certificate_track_id')
->where('application_users_id', Auth::User()->users_track_id)
->get();
return view('frontend.pages.application', compact('dataList'));
}
My view is
#foreach($dataList as $data)
<tr>
<td>{{ $data->certificate_name_en }}</td>
#if($data->application_delivery_mode == 195126)
<td>Self</td>
#else
<td>Via Post</td>
#endif
<td class="hidden-phone">{{ $data->created_at }}</td>
<td class="hidden-phone">
<span class="label label label-warning">Pending</span>
</td>
<td class="hidden-phone">
<span class="label label-primary"><i class="fa fa-edit"></i></span>
<span class="label label-danger"><i class="fa fa-trash"></i></span>
</td>
</tr>
#endforeach

This problem happens when your MySQL timezone is different from php timezone which is set in your framework.
to sync your timezone you can use following codes:
PHP:
date_default_timezone_set('Asia/Tehran');
MySQL:
$timeZone = (new DateTime('now', new DateTimeZone('Asia/Tehran')))->format('P');
$pdo->exec("SET time_zone='$timeZone';");

With Mysql attributes, you can get different values whether id or created_at(Laravel) if you use join on tables. Say you join three tables the output will return the last column of the three "created_at". Therefore you could just check to make sure your joins are correct.

You can change your timezone in Laravel in your config/app.php.
The param below can be changed to whatever your preference is in line with the supported timezones...
'timezone' => 'Europe/Dublin',

Related

Save date into database with Carbon

I'm still new in Laravel. Currently, I'm learning and working on Carbon. I already looking on every documentation and other solution but I still don't get it. I hope there is someone can teach and show me step by step how to correct or improve my code.
ComplaintController.php
public function store(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $filename,
'description' => $request->description[$item],
'report_by' => Auth::user()->id,
'created_at' => Carbon::today()->toDateString(),
'updated_at' => Carbon::now()->toDateTimeString()
);
Complaint::insert($data);
I'm saving created_at field as date only, no time and it is in the format of (yy-mm-dd).
index.blade.php
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Defect Name</th>
<th>Description</th>
<th>Image</th>
<th>Report Date</th>
<th>Due Date</th>
</tr>
</thead>
#foreach($complaint as $c)
<tr>
<td>{{$c->defect->name}}</td>
<td>{{$c->description}}</td>
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
<td>{{$c->created_at->toDateString()}}</td>
<td></td>
</tr>
#endforeach
</table>
</div>
My date is still showing finely in the table as (yy-mm-dd) but I want the date to be in format of (dd/mm/yy) so I try to use this kind of code {{$c->created_at->toDateString()->format("dd/mm/yy")}} and there is error appeared which is Call to a member function format() on string. Later on, I need to add another field for duedate and use this function addDays(30). So, what I need to do? I'm guessing that I need to put another function in my model but I can't figure out how to do it.
As mentioned by #Tim Lewis as well,
replace
{{ $c->created_at->toDateString()->format("dd/mm/yy") }}
to
{{ $c->created_at->format("dd/mm/yy") }}
As toDateString() converts it to string before changing the format.
You can also try using standard php format for datetime, instead of Carbon class,
{{ date("d/m/Y", strtotime($c->created_at)) }}
As for your second question of you want to add new table data column ,
<tr>
<td>{{ $c->defect->name }}</td>
<td>{{ $c->description }}</td>
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
<td>{{ $c->created_at->format("dd/mm/yy") }}</td>
<td>{{ $c->created_at->addDays(30) }}</td>
</tr>
This should work...
To save the date in the format dd/mm/yy, I would use the following:
date('d-m-Y', strtotime(Carbon\Carbon::now()))
To reformat the date in a view, I would use:
date('d-m-Y', strtotime($c->created_at))
I prefer to use the base php functions wherever possible to keep things simple.
If someone knows a reason not to, please let me know.
As for the adding of days,
date('d-m-Y', strtotime($c->created_at) + (60 * 60 * 24 * 30))
Should work.
Most date related problems can be solved with strtotime(), its very useful. Be sure to read up on it here: https://www.php.net/manual/en/function.strtotime.php
Casted date fields:
In Laravel the created_at and updated_at fields are casted as date fields already. So you don't have to transform this into date formats.
You can simply do
<td>{{ $c->created_at->format("d/m/y") }}</td>
Fields created_at and updated_at are also automatically filled
So you don't need to fill this fields
You can simply do
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $filename,
'description' => $request->description[$item],
'report_by' => Auth::user()->id,
);
Complaint::create($data);
Extra date field duedate
When you add custom date fields you need to cast them in the model to be date.
Add this in you model:
protected $dates = ['duedate'];

Conditional formatting in Laravel

I am new to Laravel, I am trying to format table cells as red if the current date - row date =3 months
this is how I did it: in controller
public function get_rxs()
{
$ldate = Time();
$rxs = rxs::all();
return view('viewlog', [
'rxs' => $rxs,
'ldate' => $ldate
]);
in view:
#foreach($rxs as $rx)
<tr #if($ldate-$rx->rxdate>="7776000") class="table-danger" #else #endif >
<td>{{ $rx->id }}</td>
<td>{{ $rx->pt_name }} <br></td>
<td>{{ $rx->dr_name }}</td>
<td>{{ date("Y-m-d",$rx->rxdate) }}</td>
and i got the time saved as integer (epoch) the thing is it is calculating sec:min:hr and i really do not want to include that in the calculation since it may make it a split second difference between red formatting and regular and i want it to always use 00:00:00 time and whatever date it is.. how to do that.. I tried doing it with date() but it says invalid numerical data since i think date returns chars with numbers..
Change
<tr #if($ldate-$rx->rxdate>="7776000") class="table-danger" #else #endif >
to
<tr class="{{ ($ldate->$rx->rxdate >= "7776000") ? 'table-danger' : ''}}">
I simply used carbon dependencies and it worked like a charm
Like this:
1. added use Carbon\Carbon; in the controller
2. Channged $ldate to this $ldate = Carbon::now()
3. in the view I added this after foreach
<tr class="#if($ldate->diffindays($rx->rxdate)>="90") table-danger #elseif($ldate->diffindays($rx->rxdate)>="60") table-warning #endif" >>
and it started showing difference in days only
So I stopped using epoch format and used DateTime format instead

Select values from a table where Ids are in json format in another table in laravel

I have a table named journal_details and it has a column named transaction_by_to. I am saving account_head_id values as json_encode format in transaction_by_to in table journal_details. Now I want to run a select query to get account head names from account_heads where transaction_by_to ids in JSON format will find the id from account_heads. In the controller, I tried something like bellow, but it's getting only one. But I want to show all from account_heads for all JSON formatted ids.
public function ledgerSubmit(Request $request)
{
$acId = $request->acount_head;
$startDate = Carbon::parse($request->start_date)->format('Y-m-d');
$endDate = Carbon::parse($request->end_date)->format('Y-m-d');
$reportType = $request->report_type;
$nameOfAccount = AccountHead::find($acId);
$ledgers = DB::table('journal_details')
->join('journals', 'journal_details.journal_id', '=', 'journals.id')
->join('account_heads', 'journal_details.account_head_id', '=', 'account_heads.id')
->where('journal_details.account_head_id', $acId)
->select('journals.number as journalNo', 'journals.journal_date as journalDate', 'journal_details.*', 'account_heads.name as nameOfAccount')
->get();
if (count($ledgers)) {
$transactionByToId = $ledgers[0]->transaction_by_to;
foreach (json_decode($transactionByToId) as $tId) {
$transactionByTo = AccountHead::where('id', $tId)->get();
}
}
return view('report.ledger.searched-result', compact('reportType', 'startDate', 'endDate', 'ledgers', 'transactionByTo', 'nameOfAccount'));
}
And in blade view-
#foreach($ledgers as $ledger)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $ledger->journalNo }}</td>
<td>{{ date('jS F, Y', strtotime($ledger->journalDate)) }}</td>
<td>{{ $ledger->nameOfAccount }}</td>
<td>
{{ $transactionByTo[0]->name }}
</td>
<td>
{{ number_format($ledger->debit, 2,".",",") }}
</td>
<td>
{{ number_format($ledger->credit, 2,".",",") }}
</td>
</tr>
#endforeach
["16","17","7","11"] is transaction_by_to column values in json format in journal_details and these ids are id for account_heads table.
There are several errors in your code, like in following code:
foreach (json_decode($transactionByToId) as $tId) {
$transactionByTo = AccountHead::where('id', $tId)->get();
}
it will always keep single value, the last value. So it will seem that there is only one record.
But why don't you do following to get all records at a time:
$accountHeadIds = json_decode($transactionByToId, true);
$accountHeads = AccountHead::whereIn('id', $accountHeadIds)->get();
Secondly, I don't see you are processing Account Head variable (as per my code example, $accountHeads) in the view file that is not part of $leders variable. If you want to have that under $ledgers variable then you should store under it.
Note: I haven't tested the code above, but the concept is similar.

Laravel time table

I am making a time table in Laravel where user can select one field at say 10:00, and reserve equipment until say 12:00.
I have trouble displaying the range from when to when the equipment is reserved
#while($scheduler_start_time < $scheduler_end_time)
<tr>
<td>{{$scheduler_start_time->format('H:i:s')}}</td>
#foreach($equipment as $instrument)
<td>
<a href="#">
#if($instrument->reservations->where('reserved_from','=', $scheduler_start_time)
->where('reserved_to','<=', $scheduler_end_time)->first() != null)
HERE
#else
#endif
</a>
</td>
#endforeach
<?php $scheduler_start_time->addMinutes(30) ?>
</tr>
#endwhile
One instrument can have many reservations:
And this is what I get when getting reservation where reserved_from equals time. If I use >= I am fetching both records. I need a way to see that for example: Instrument3 is reserved from 6:30 up to 7:30, and then from 9:30 to 10:00
Unless I misunderstood your problem, I think you just need to add an upper limit on the 'reserved_from'. Would this work?
#if($instrument->reservations->where('reserved_from','>=', $scheduler_start_time)->where('reserved_from', '<', $scheduler_end_time)->where('reserved_to','<=', $scheduler_end_time)->first() != null)
UPDATE: Solved by OP
#if($instrument->reservations ->where('reserved_from','<=', $scheduler_start_time) ->where('reserved_to','>=', $scheduler_start_time)->first() != null

Trying to get property of non-object - retrieve set of data in laravel 5.0

I'm having this issue with laravel when I'm getting data from two tables.This is my query. It exists in a controller.
$switches = DB::table('sw_pairs')->
join('cust_sw_pair','cust_sw_pair.sw_pair_id', '=', 'sw_pairs.sw_pair_id')->
select(
DB::raw(
'cust_sw_pair.sw_pair_id,
count(cust_sw_pair.sw_pair_id) as totcount,
pri_sw, sec_sw,
count(if(pri_sw_admin_status="Admin Down" AND sec_sw_admin_status="Admin Down", 1, NULL)) as downCount')
)->
groupBy('cust_sw_pair.sw_pair_id')->get();
When I execute this query I get this error.
"Trying to get property of non-object"
but the above query is succesfully returning the first row of the result set when I used first() instead of the get() method.
This is the retrieving part which exists on the view:
#foreach($switches as $switch_pair)
<tr>
<td>{{$switches->pri_sw}} / {{$switches->sec_sw}}</td>
<td><span>{{$switches->downCount}},{{$switches->totcount}</span></td>
<td><i class="fa fa-level-up"></i> 40% </td>
<td>{{$switches->downCount}} / {{$switches->totcount}}</td></tr>
#endforeach
How can I successfully get all the results?
There are two problems with your code:
a) you are looping through $switches but are not using the single items within the loops
b) missing accolade in the second td
So to give you the result of the above fixed:
#foreach($switches as $switch_pair)
<tr>
<td>{{ $switch_pair->pri_sw }} / {{ $switch_pair->sec_sw }}</td>
<td><span>{{ $switch_pair->downCount }},{{ $switch_pair->totcount }}</span></td>
<td><i class="fa fa-level-up"></i> 40% </td>
<td>{{ $switch_pair->downCount }} / {{ $switch_pair->totcount }}</td></tr>
#endforeach

Categories