Hamza
Hamza

Reputation: 122

how to get specific date result in laravel?

example i am passing this date in $date = 2020-12-28 15:15:53

and

in db approve_date = 2020-12-28 15:15:00

i am trying to get all the record of date only like this 2020-12-28

so i tried

public function getdatedInvoice($date)
    {
     
        $invoices = Invoice::where('user_id' , Auth::id())->where('is_approved' , 1)->whereDate('approve_date' , $date)->get();
        dd($invoices);
        return view('approved_invoices', compact('invoices'));
    }

but when i try to use whereDate it gives me nothing how i can get that data according to date?

Upvotes: 1

Views: 904

Answers (2)

Babalola Macaulay
Babalola Macaulay

Reputation: 359

First of all, by default, Laravel will only process the approve_date column from your database as a string, even if you set it as a date_time column.

To make Laravel process it as a real date instead, you need to add this to the top of your Invoice model:

class Invoice extends Model {
    protected $dates = [
        'approve_date'
    ];
}

Now you will be able to make date comparisons without getting weird errors.

To make your date formatted the way you want, you can go about it in 2 ways.

  1. You can either set a default date formats on every date column in your model by adding this also to the model:

    protected $dateFormat = 'Y-m-d';
    

    https://laravel.com/docs/5.2/eloquent-mutators#date-mutators

  2. You can also do this at runtime in your view: {{ \Carbon\Carbon::parse($invoice->approve_date)->format('Y-m-d') }}

Upvotes: 1

JS_LnMstr
JS_LnMstr

Reputation: 378

  1. 'approve_date' is not a variable... you are missing the $ sign. It should be something like this:

    $invoices = Invoice::where('user_id' , Auth::id())->where('is_approved' , 1)->whereDate('$approve_date' , $date)->get();

  2. that variable is not being declared in the function;

  3. After all that, you have your date like date/time and you should convert the format using (for example) Carbon https://carbon.nesbot.com/docs/

Upvotes: 2

Related Questions