Josadec Pedraza
Josadec Pedraza
Laravel
Comparte:

Livewire buscar fecha con formato

Hola que tal, espero esten bien.
Estoy intentando hacer busquedas de fechas en una tabla desde un input llamado Search pero al hacer la busqueda no encutra nada, por que el formato que busco no concuerda con el formato de la BD, ejemplo: busco "16/03/2022" pero en la DB esta "2022-03-16" y creo que eso es el problema.
Intente usar el Casts pero no funciona o no se usarlo o que... Ayuda 
-- Model --
class Holiday extends Model
{
    use HasFactory;

    protected $fillable =['name','holiday','comments'];

    protected $casts =[
        'search' => 'date:Y-m-d'
    ];

    public function getRouteKeyName()
   {
     return "name";
   }
   
}
Livewire Class Component
class HolidaysIndex extends Component
{
    use WithPagination;

    protected $paginationTheme = "Bootstrap";

    protected $casts =[
        'search' => 'date:Y-m-d'
    ];

    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 updatedReminder()
    {
        $this->search =Carbon::createFromFormat('Y-m-d',$this->search);
    }

    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()
    {
        $holidays = Holiday::Where('name','like',"%{$this->search}%")
        ->Orwhere('date','like',"%{$this->search}%")
        ->Orwhere('comments','like',"%{$this->search}%")
        ->orderBy($this->sortField,$this->sortDirection)
        ->paginate($this->perPage);

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

Livewire Component
<div class="card-body">
        <table class="table table-script">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>NAME</th>
                    <th>DATE</th>
                    <th>COMMENTS</th>
                    <th colspan="2"></th>
                </tr>
            </thead>

            <tbody>
                @forelse ($holidays as $holiday)
                    <tr wire:loading.class='opacity-25'>
                        <td>{{ $holiday->id }}</td>
                        <td>{{ $holiday->name }}</td>
                        <td>{{ date('m/d/Y', strtotime($holiday->date)) }}</td>
                        <td>{{ $holiday->comments }}</td>
                        <td width="10px">
                            <a href="{{ route('admin.holidays.edit',$holiday) }}" class="btn btn-primary btn-sm">{{ __('Edit') }}</a>
                        </td>
                        <td width="10px">
                            <form action="{{ route('admin.holidays.destroy',$holiday) }}" method="POST">
                                @csrf
                                @method('delete')
                                <button type="submit" class="btn btn-danger btn-sm">{{ __('Delete') }}</button>
                            </form>
                        </td>
                    </tr>
                @empty
                        <td colspan="5" 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>

Gracias...
gssa
gssa (986 xp)
Hola Josadec, hay varias formas de realizar esto
* crear un formrequest, para que solo permitas el uso de un tipo de formato y "normalices" el formato que requieres para utilizar en base de datos
* utilizar la libreria de Carbon aqui puedes realizar modificaciones y manipular el formato de las fechas desde el backend  https://carbon.nesbot.com/docs/ 
* Utilizar mutadores, para que puedas realizar las modificaciones que requieres, igual usando Carbon o alguna otra herramienta que estes considerando utilizar
Te dejo un par de lecciones dentro de aprendible, para que revises lo que comento respecto a mutadores
https://aprendible.com/series/desarrollo-blog/lecciones/reestructuracion-del-postscontroller
https://aprendible.com/series/desarrollo-blog/lecciones/accesores-y-mutadores-de-eloquent
Josadec Pedraza
Josadec Pedraza (392 xp)
Fijate que intente hacer eso que dice los videos pero ni asi funciona cuando hago el mutador con accessor nada meda el mismo error sabes si estoy haciendo algo mal.

Tal vez no me exlicque correctamente "Intento hacer un live serach y que al filtar por fecha reconosca el formato m/d/Y"  eso es todo porque MySQL lo pone con formato de Unix Y-m-d 

Espero me puedas dar mas informacion de como resolver esto

Gracias 

```
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');
    }
}

```
Josadec Pedraza
Josadec Pedraza (392 xp)
Hola amigo gssa,

La verdad utilice las recomendaciones que me indicaste pero no funciono o no se si las hice correctamente, pero esta fue como lo solucione

creo que es mucho codigo pero no encontre una mejor forma

en el render de la clase de Livewire hice lo siguiente
 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);

        }