jeudi 29 octobre 2015

How to use andersao/l5-repository criteria feature to filter records in controllers in Laravel 5?

So I am working with andersao/l5-repository and I am trying to filter out records using the criteria feature.

So I created my own Criteria as follows:

<?php
namespace Archive\Criterias;

use Illuminate\Http\Request;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

class OrderIdRequestCriteria implements CriteriaInterface
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Apply criteria in query repository
     *
     * @param $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $order_id = $this->request->get('order_id');

        if(!isset($order_id)) {
            return $model;
        }

        // dd($order_id);

        $model->where('order_id', '=', $order_id);

        return $model;
    }

}

And then in my controller after importing it and the repository, the index method looks like so:

public function index(Request $request)
{
    $this->documentRepo->pushCriteria(new OrderIdRequestCriteria($request));
    $documents = $this->documentRepo->paginate(20);

    return jsend()->success()
                  ->message("Resource Fetched Successfully")
                  ->data($documents->toArray())
                  ->get();
}

And yet when I pass order_id as a GET variable, I still see all the other documents which do not belong to that order. What am I doing wrong? And moreover if I uncomment the dd() in the OrderIdRequestCriteria class, I see the order_id dumped correctly which means the code is running fine.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire