Show todays article using Laravel 5 and Carbon - laravel-5

I'm trying to show a daily article using Laravel 5 and carbon. I have converted the published_at string to a carbon object so I can get just the day to compare. I just can't figure out the where clause would be.
//this is in my model to make it a carbon object
protected $dates = ['published_at'];
//method in my controller
public function current()
{
$article = Article::where('published_at', '>=', Carbon::now())->first();
//testing prints 2 but today is the 1st
dd($article->published_at->day);
return view('articles.show')->with('article', $article);
}

For checking if a timestamp is from today, the DATE() function comes in handy:
$today = Carbon::now()->toDateString();
$article = Article::whereRaw('DATE(published_at) = ?', [$today])->first();

Related

Laravel Carbon class timestamp

In my laravel project I didn't migrate the table with timestamp(created_at). I used to get the time with a date column.
I need to filter the data from that table so that I used Laravel Carbon class.
This is my function for filter the data
public function getWeeklyData()
{
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
return view('admin.pages.tables.weeklydata',['weeklydata' => $weeklydata]);
}
But there is no output.
Some times my date format is different from Carbon class date format.
If any solution for this?
When you use Carbon it will carbon object return. so try below
$data = \Carbon\Carbon::today()->subDays(7)->format('Y-m-h');
$weeklydata=DB::table('response')->where('date','>=',$data)
->get();
and you can use whereDate also
$data = \Carbon\Carbon::today()->subDays(7);
$weeklydata=DB::table('response')->whereDate('date','>=',$data)
->get();

How to input the date from YYYY-MM-DD to DD-MM-YYYY in laravel

Some people know how to change the YYYY-MM-DD format to become DD-MM-YYYY when inputting to the database and how to display it from the database.
StudentsController.php
public function store(Request $request)
{
//
$students = new Student();
$students->nis = $request->nis;
$students->nama = $request->nama;
$students->jk=$request->jk;
$students->nama_sekolah = $request->nama_sekolah;
$students->alamat_sekolah = $request->alamat_sekolah;
$students->tanggal_mulai = $request->tanggal_mulai;
$students->tanggal_selesai=$request->tanggal_selesai;
$students->email=$request->email;
$students->alamat_siswa=$request->alamat_siswa;
$students->no_hp=$request->no_hp;
$students->email_siswa=$request->email_siswa;
$students->nama_guru=$request->nama_guru;
$students->save();
return back()->with('success','Data Berhasil Ditambahkan');
}
PHP can parse most date formats automatically, so to parse either format you can just create a Datetime or Carbon with the date string as the first argument.
Laravel can then automatically transform Datetime and Carbon instances to the correct format for your database, so you can do something like:
$dateX = new Carbon($request->get('date_attr')
$students = new Student();
// other attributes
$students->date = $dateX;
$students->save();
return back()->with('success','Data Berhasil Ditambahkan');
MySQL expects date to be formatted like YYYY-MM-DD. So while saving data to the database keep it as it is. When you are displaying the date, you can format it as you wish. To do so make your date as a date in your model.
class Student extends Model
{
protected $guarded = [];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['date'];
}
Now you can format your date attribute anywhere like
$student->date->format("d-m-Y")
It will give you the date in DD-MM-YYYY format.
In Laravel 5, you can do it using carbon class.
\Carbon\Carbon::parse('2019-04-24')->format('d-m-Y');
Use the strtotime date format:
date("d-m-Y", strtotime($date));

laravel-5.4 : get records that is created_at from yesterday at 5 o'clock until now

I need to get the records that is created from yesterday at 5.00PM until now so if I try the following:
If I open the system at 8am query start yesterday 5pm until now (8am)
If I open the system at 1pm query start yesterday 5pm until now (1pm)
... and so on
Here is my function.
public function allNewOrdersToday() {
$allNewOrders = ( new OrderList() )
->where( 'created_at', '>=', Carbon::yesterday() )
return $allNewOrders;
}
Using Carbon, you should be able to query where the date is beyond Yesturday 5:00pm using the yesturday() and setTime() carbon methods:
use Carbon\Carbon;
...
public function allNewOrdersToday() {
return OrderList::whereDate('created_at', '>=', Carbon::yesterday()->setTime(17, 00, 00)->toDateTimeString())
->get();
}
In this example, I have changed (new OrderList()) to OrderList::... as you are using eloquent models and are able to call query builder methods without needing a new instance of the class.
Try to do like this:
public function allNewOrdersToday() {
$allNewOrders = ( new OrderList() )
->whereDate( 'created_at', '>=', date('Y-m-d 17:00:00',strtotime("-1 days"))
return $allNewOrders;
}

Laravel Eloquent - How to query all car models of given year where make is given?

I have these tables: Models, Year and Model_Year. The Model table has a make_id column referencing an id in Make table.
In my model I have defined a belongsToMany relationship between Model and Year.
This is what am doing so far in controller:
public function getModels() {
$year = Year::findOrFail(1);
$make = Vmake::findOrFail(1);
$models = $year->model->pluck('name','id');
return response()->json($models);
}
This returns all models of year with id 1.
How do I add a query to get only models where make_id = 1?
there is a simple solution for this. You just need to change function as I given below
public function getModels() {
$year = Year::findOrFail(1);
$make = Vmake::findOrFail(1);
$models = $year->model()
->where('make_id', 1)
->pluck('name','id');
return response()->json($models);
}
above is the changed code. Try and let me know if that not works for you.

Laravel Add Additional Rows to an Eloquent Object

I want to add an "On This Day" feature which should display records from The Previous Years. I have some Entries, all of them have a 'date' attribute. This is what I've been trying so far:
public function filterByDay($id){
$entries = Entry::where('id', $id)->get();
$currentDay = $entries[0]->date;
$oldestYear = Entry::orderBy('date','asc')->first()->date;
$previousYear = $currentDay;
while($previousYear >= $oldestYear ){
$previousYear = $currentDay->subYear();
$entries->push(Entry::where('date', $previousYear)->get());
}
return view('home')->with(compact('entries'));
}
I must send a Collection of "Entry" type from this controller method so that I can use $entry->title etc in the view. But whenever I'm using $entries->push(...) , I'm getting a Collection instance, not Entry instance. How can I convert the Collection back into Entry instance? Or what is the alternative? I'm using Laravel 5.5. Some help will be much appreciated.
You can combine whereDay, whereYear and whereMonth methods to achieve it in one liner:
$entries = Entry::where('id', $id)->get();
$today = Carbon\Carbon::now();
$oldestYear = Entry::orderBy('date','asc')->first()->date;
$allEntries = Entry::whereDay('date', $today->day)
->whereYear('date', '>=', $oldestYear)
->whereMonth('date', $today->month)
->get();
return view('home')->with(compact('allEntries'));

Resources