how to format date to search

I need to format the date to search, since the date that comes from the variable is the example 2021-09-03, without the time and the one from the database comes with the time. I only need to look for the date, not the time.

SaleController.php

public function index()
{
    $idUser = Auth::id();
    $search = request('calendar');

    $sale = Sale::with('client', 'products')->where('user_id', '=', $idUser)->where("DATE_FORMAT(updated_at, '%Y-%m-%d')", '=', $search)->get();

    
   //Here it throws an error because it is misspelled


    return $sale;
}

I only need to look for the date, not the time.

enter image description here

Upvotes: 0

Views: 176

Answers (2)

Sylvester Oguikpu
Sylvester Oguikpu

Reputation: 569

You could do this when filtering for date ranges:

$start_date = $request->start_date;
$end_date = $request->end_date;

$sale = Sale::whereBetween('created_at', [$start_date, $end_date])->with('client', 'products')->where('user_id', '=', $idUser)->get()

or this as in your own use case

$search = request('calendar');

$sale = Sale::where('created_at', $search )->with('client', 'products')->where('user_id', '=', $idUser)->first();

To reduce the amount of data loaded for each query, you could refactor your query to:

$search = request('calendar');

$sale = Sale::where('user_id', '=', $idUser)->with('client', 'products')->where('created_at', $search )->first();

Note the use of "first()" instead of "get()" first() returns an object while get() returns an array.

Upvotes: 2

brice
brice

Reputation: 1891

You can use the whereRaw query builder method for raw SQL expressions:

$sale = Sale::with('client', 'products')->where('user_id', '=', $idUser)->whereRaw("DATE_FORMAT(sales.updated_at, '%Y-%m-%d') = '?'", [$search])->get();

See: https://laravel.com/docs/8.x/queries#whereraw-orwhereraw

Upvotes: -1

Related Questions