Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Josadec's avatar

Help Livewire live search date with format m/d/Y

MySQL uses Unix date format to save data in the tables but when I need to search with a specific format example "m/d/Y" the live search not found results

I use an input-type search to be able to filter dates and show the results in a table

I tried using Accessor with Mutators but for a reason, it doesn't work

Someone could help me?

Model Classs

class Order extends Model
{
    use HasFactory;

    protected $fillable=['status_id','number','slug','need_by_date','lockers_qty','shipping_days','pdf','comments'];

   /*  protected $dates = ['need_by_date' => 'date:m/d/Y']; */

    /* 
        public function setNeedByDateAttribute($search)
        {
          $this->attributes['need_by_date'] = (new Carbon($search))->format('m/d/Y');
        }

    */

    public function getNeedByDateAttribute()
    {
      return date('m/d/Y',strtotime($this->attributes['need_by_date']));
    }

    public function setNeedByDateAttribute($search)
    {

      $this->attributes['need_by_date'] = Carbon::createFromDate('Y-m-d',$search)->format('m/d/Y');
    }

    public function getRouteKeyName()
    {
      return "slug";
    }

    public function turn()
    {
        return $this->belongsTo(Turn::class);
    }

    public function status()
    {
      return $this->belongsTo(Status::class);
    }
}

Livewire component


class OrdersIndex extends Component
{
    use WithPagination;

    protected $paginationTheme = "Bootstrap";

    public $search ="";

    public $perPage = "10";

    public $sortField = "created_at";

    public $sortDirection = "desc";

    public $querySearch = 
    [
        'search' => ['except' => ''],
        'perPage' => ['except' => '10']
    ];

    public function clear()
    {
        $this->search = "";
        $this->page = 1;
        $this->perPage = '10';
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if($this->sortField === $field)
        {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        }else
        {
            $this->sortDirection = 'asc';
        }   
        $this->sortField = $field;
    }
    

    public function render()
    {
        $today = Carbon::today();

        $orders = Order::WhereHas('status', function ($qty){
            return $qty->where('name','like',"%{$this->search}%");
        })
        ->Orwhere('number','like',"%{$this->search}%")
        ->Orwhere('slug','like',"%{$this->search}%")
        ->Orwhere('need_by_date','like',"%{$this->search}%")
        ->Orwhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

        
        return view('livewire.admin.orders.orders-index',compact('orders','today'));
    }
}

Livewire View

<div>
    <div class="card">
        <div class="card-header">
            
            <div class="input-group mb-2">
                <span class="input-group-text" id="basic-addon1"><i class="fas fa-search"></i></span>
                <input wire:model="search" type="search" class="form-control" placeholder="Search...">
            </div>
        </div>
        <div class="card-body">
            
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>NUMBER</th>
                        <th>SLUG</th>
                        <th>NEED BY DATE</th>
                        <th>LOCKERS QTY</th>
                        <th>SHIPPING BUSSINES DAYS</th>
                        <th>STATUS</th>
                        <th>PDF</th>
                        <th>COMMENTS</th>
                        <th colspan="2"></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($orders as $order)
                        <tr>
                            <td>{{ $order->id }}</td>
                            <td>{{ $order->number }}</td>
                            <td>{{ $order->slug }}</td>
                            <td>
                                <span class="p-2 rounded
                                    @if ($order->need_by_date <= Carbon\Carbon::today())
                                        bg-danger
                                    @else
                                        bg-success
                                    @endif"> 
                                    {{ date('m/d/Y',strtotime( $order->need_by_date)) }} 
                                </span>
                            </td>
                            <td>{{ $order->lockers_qty }}</td>
                            <td>{{ $order->shipping_days }}</td>
                            <td> <span class="bg-{{ $order->status->color }} p-2 rounded">{{ $order->status->name }}</span></td>
                            <td> <a href="{{ asset('storage/'.$order->pdf ) }}" target="_blank" class="btn btn-info opacity-10"><i class="fas fa-file-pdf"></i></a></td>
                            <td>{{ $order->comments }}</td>
                            <td width="10px">
                                <a href="{{ route('admin.orders.edit',$order) }}" class="btn btn-primary btn-sm">{{ __('Edit') }} </a>
                            </td>
                            <td width="10px">
                                <form action="{{ route('admin.orders.destroy',$order) }}" method="post">
                                    @csrf
                                    @method('delete')

                                    <button type="submit" class="btn btn-danger btn-sm">{{__('Delete') }}</button>
                                </form>
                            </td>
                        </tr>
                    @empty
                            <td colspan="9" class="py-4 ">
                                <div class="d-flex justify-content-center align-items-center border rounded bg-primary my-6">
                                    <span class="fs-12">
                                        No order Found...
                                    </span>
                                    <span class="py-10">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-exclamation-diamond" viewBox="0 0 16 16">
                                            <path d="M6.95.435c.58-.58 1.52-.58 2.1 0l6.515 6.516c.58.58.58 1.519 0 2.098L9.05 15.565c-.58.58-1.519.58-2.098 0L.435 9.05a1.482 1.482 0 0 1 0-2.098L6.95.435zm1.4.7a.495.495 0 0 0-.7 0L1.134 7.65a.495.495 0 0 0 0 .7l6.516 6.516a.495.495 0 0 0 .7 0l6.516-6.516a.495.495 0 0 0 0-.7L8.35 1.134z"/>
                                            <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z"/>
                                          </svg>
                                    </span>
                                </div>
                            </td>
                    @endforelse
                </tbody>
            </table>
            <div class="card-footer">
                {{ $orders->links(); }}
            </div>
        </div>
    </div>
</div>
0 likes
6 replies
LaryAI's avatar
Level 58

The issue is that the date format used in the search input is different from the date format stored in the database. The solution is to convert the search input to the database date format before performing the search. This can be done in the Livewire component's render method by using the Carbon library to parse the search input and convert it to the database date format.

Here's an updated version of the render method that performs the date conversion:

public function render()
{
    $today = Carbon::today();

    $searchDate = Carbon::createFromFormat('m/d/Y', $this->search)->format('Y-m-d');

    $orders = Order::WhereHas('status', function ($qty){
            return $qty->where('name','like',"%{$this->search}%");
        })
        ->orWhere('number','like',"%{$this->search}%")
        ->orWhere('slug','like',"%{$this->search}%")
        ->orWhere('need_by_date', $searchDate)
        ->orWhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

        
    return view('livewire.admin.orders.orders-index',compact('orders','today'));
}

In this updated version, we first use Carbon::createFromFormat to parse the search input as a date with the format m/d/Y. We then use format to convert this date to the database date format Y-m-d. Finally, we use this converted date in the orWhere clause for the need_by_date field in the search query.

Note that we're assuming that the database date format is Y-m-d. If it's different, you'll need to adjust the format method accordingly.

Also note that we're not using any accessors or mutators in the Order model. The getNeedByDateAttribute and setNeedByDateAttribute methods can be removed.

Josadec's avatar

@LaryAI Doesn't work I have this issue now

Carbon\ Exceptions\InvalidFormatException

Data missing

 public function render()
    {
        $today = Carbon::today();

        $testDate = Carbon::createFromFormat('m/d/Y', $this->search, null)->format('Y-m-d');

        $orders = Order::WhereHas('status', function ($qty){
            return $qty->where('name','like',"%{$this->search}%");
        })
        ->Orwhere('number','like',"%{$this->search}%")
        ->Orwhere('slug','like',"%{$this->search}%")
        ->Orwhere('need_by_date','like',"%{$this->search}%")
        ->Orwhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

        
        return view('livewire.admin.orders.orders-index',compact('orders','today'));
    }
AungHtetPaing__'s avatar

@Josadec that is because you don't have search date when first render. You have to use conditional when clause.

 public function render()
    {
        $today = Carbon::today();

        $orders = Order::whereHas('status', function ($qty){
            return $qty->where('name','like',"%{$this->search}%");
        })
        ->orWhere('number','like',"%{$this->search}%")
        ->orWhere('slug','like',"%{$this->search}%")
		->when($this->search, function($query) {
			$testDate = Carbon::createFromFormat('m/d/Y', $this->search, null)->format('Y-m-d');

			$query->orWhere('need_by_date', $testDate);
		}
        ->orWhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

        
        return view('livewire.admin.orders.orders-index',compact('orders','today'));
    }

And your need_by_date format must be Y-m-d. You should write syntax correctly orWhere not Orwhere and whereHas not WhereHas.

Josadec's avatar

@AungHtetPaing__ Hey bro, for me that makes sense, but when I tried to run this I have the same problem

Carbon\Exceptions\InvalidFormatException
Data missing

Carbon\Carbon : 676 "rawCreateFromFormat"

      $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time;

            }



            // Regenerate date from the modified format to base result on the mocked instance instead of now.

            $date = self::createFromFormatAndTimezone($format, $time, $tz);

        }



        if ($date instanceof DateTimeInterface) {

            $instance = static::instance($date);

            $instance::setLastErrors($lastErrors);



            return $instance;

        }



        if (static::isStrictModeEnabled()) {

            throw new InvalidFormatException(implode(PHP_EOL, $lastErrors['errors']));

        }



        return false;

    }



    /**

     * Create a Carbon instance from a specific format.

     *

     * @param string                         $format Datetime format

     * @param string                         $time

     * @param DateTimeZone|string|false|null $tz

     *

     * @throws InvalidFormatException

     *

Carbon\Carbon :699 "createFromFormat"

 *

     * @param string                         $format Datetime format

     * @param string                         $time

     * @param DateTimeZone|string|false|null $tz

     *

     * @throws InvalidFormatException

     *

     * @return static|false

     */

    #[ReturnTypeWillChange]

    public static function createFromFormat($format, $time, $tz = null)

    {

        $function = static::$createFromFormatFunction;



        if (!$function) {

            return static::rawCreateFromFormat($format, $time, $tz);

        }



        if (\is_string($function) && method_exists(static::class, $function)) {

            $function = [static::class, $function];

        }



        return $function(...\func_get_args());

    }



    /**

     * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()).

     *

     * @param string                                             $format     Datetime format

     * @param string  

App\Http\Livewire\Admin\Orders\OrdersIndex : 66 App\Http\Livewire\Admin\Orders{closure}

           $this->sortDirection = 'asc';

        }

        $this->sortField = $field;

    }





    public function render()

    {

        $today = Carbon::today();



            $orders = Order::WhereHas('status', function ($qty){

                return $qty->where('name','like',"%{$this->search}%");

            })

            ->orWhere('number','like',"%{$this->search}%")

            ->orWhere('slug','like',"%{$this->search}%")

            ->when($this->search, function ($qty){

                $dateformat = Carbon::createFromFormat('m/d/Y', $this->search, null)->format('Y-m-d'); //Here is select the error

                $qty->orWhere('need_by_date',$dateformat);

            })

            ->orWhere('need_by_date','like',"%{$this->search}%")

            ->orWhere('comments','like',"%{$this->search}%")

            ->orderBy($this->sortField,$this->sortDirection)

            ->paginate($this->perPage);
AungHtetPaing__'s avatar

@Josadec not sure why are you still getting error. try after remove third parameter from createFromFormat it doesn't require.

Josadec's avatar

@AungHtetPaing__ Well, finally I found a solution, but I think it was not the best way but its works.

In the render function, I make this

Livewire Class

public function render()
    {

        $orders = Order::whereHas('status', function ($qty){
            return $qty->where('name','like',"%{$this->search}%");
        })
        ->orWhere('number','like',"%{$this->search}%")
        ->orWhere('slug','like',"%{$this->search}%")
        ->when($this->search, function ($qty){
            if(str_contains($this->search,'/')){
                $slash = str_replace('/','-',$this->search);
                $qty->orWhere('need_by_date','like',"%{$slash}%");
                }
            })
        ->orWhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

        if (substr_count($this->search,'/')==2) {
            $dateFormat = date('Y-m-d',strtotime($this->search));
            
            $orders = Order::whereHas('status', function ($qty){
                return $qty->where('name','like',"%{$this->search}%");
            })
            ->orWhere('number','like',"%{$this->search}%")
            ->orWhere('slug','like',"%{$this->search}%")
            ->orWhere('need_by_date','like',"%{$dateFormat}%")
            ->orWhere('comments','like',"%{$this->search}%")
            ->orderBy($this->sortField,$this->sortDirection)
            ->paginate($this->perPage);

        }
                
            
        return view('livewire.admin.orders.orders-index',compact('orders'));
    }

Please or to participate in this conversation.