Khirad Zahra
Khirad Zahra

Reputation: 893

How to convert this Raw query into Laravel Eloquent way?

This is my raw query.

DB::raw("SELECT * FROM tble WHERE status=1 and now() BETWEEN start_time and end_time ORDER BY id DESC LIMIT 1")

How to convert this into Laravel Eloquent ?

Upvotes: 0

Views: 582

Answers (3)

StateLess
StateLess

Reputation: 5402

DB::table('tble')::where('status',1)
                 ->where('start_time', '<=', Carbon::now())
                 ->where('end_time', '>=', Carbon::now())
                 ->orderBy('id')
                 ->first();

You can use simple date handling package Carbon to achieve this.

Upvotes: 1

A.khalifa
A.khalifa

Reputation: 2496

Try this

 DB::table('tble')::where('status',1)
                      ->whereBetween(Carbon::now(), ['start_time', 'end_time'])
                      ->orderBy('id')
                      ->first();

Upvotes: 0

Sandeesh
Sandeesh

Reputation: 11906

Create a model for the table app/Table.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Table extends Model
{
    protected $table = 'tble';
}

Logic

$now = \Carbon\Carbon::now();

$result = \App\Table::where('status', 1)
    ->where('start_time', '<=', $now)
    ->where('end_time', '>=', $now)
    ->orderBy('id')
    ->first();

Upvotes: 2

Related Questions