Hi to every one, I new in this laravel world. I need some help. I have this table.
MariaDB [qualmedDB]> select * from backup_models;
+----+---------------------+---------------------+---------+---------------------+
| id | created_at | updated_at | name | date |
+----+---------------------+---------------------+---------+---------------------+
| 1 | 2023-12-04 22:34:13 | 2023-12-04 22:34:13 | Jhon| 2023-12-04 22:34:13 |
| 2 | 2023-12-04 22:36:33 | 2023-12-04 22:36:33 | Jhon| 2023-12-04 22:36:33 |
| 3 | 2023-12-04 22:41:04 | 2023-12-04 22:41:04 | Carl| 2023-12-04 22:41:04 |
+----+---------------------+---------------------+---------+---------------------+
Then i like to show the last date for each name. In this case
Jone - 2023-12-04 22:36:33 Carl - 2023-12-04 22:41:04
For the momento i try this without success.
public function index()
{
$object = DB::table('backup_models')
->select('id', 'name','created_at')
->orderBy('date', 'desc')
->groupBy('name')
->get();
return view('backup.index',[ 'object' => $object ]);
}
I change it to asc
but does't work.
And ->orderBy('date', 'desc')
changed to ->orderBy('id', 'desc')
it show the first Jhon date (2023-12-04 22:34:13)
the migrate is
public function up(): void
{
Schema::create('backup_models', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string("name");
$table->string("date");
});
}
change your date column in migration file like this : $table->date('date');
The SQL sentence is this :
select * from backup_models where date IN (SELECT MAX(date) FROM backup_models GROUP BY name);
and the solution was this:
public function index()
{
$object = DB::table('backup_models')
->whereIn('date', function($query) {
$query->select(DB::raw('MAX(date)'))
->from('backup_models')
->groupBy('name');
})
->get();
return view('backup.index',[ 'object' => $object ]);
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community