Doubt join with paginate laravel

1

How to mount eloquent the following query?

SELECT * FROM nos.destinos d join nos.servidors s on (d.idservidor = s.idservidor)
where s.servidor  like '%nome%' 

My templates

class Servidor extends Model
{
    protected $primaryKey = 'idservidor';

    public function destino(){
        return $this->hasmany('App\Destino', 'idservidor', 'idservidor');
    }
}

class Destino extends Model
{
    protected $primaryKey = 'iddestino';

    public function servidor(){
        return $this->belongsTo('App\Servidor', 'idservidor', 'idservidor');
    } 
}

Controller

public function index ()     {         $ destinations = new Destination;

         if(request()->has('perpage')) {
             session(['perPage' => request('perpage')]);
         }

         // filtros

         if (request()->has('servidor')){
            if (request('servidor') != ""){

                 $destinos = $destinos->join('servidors', 'destinos.idservidor', '=', 'servidors.idservidor')
                ->select('destinos.*', 'servidors.servidor')
                 ->where('servidors.servidor', 'like', '%' . request('servidor') . '%')->get();

            }
        }


        if (request()->has('iddestino')){
             if (request('iddestino') != ""){

                $destinos = $destinos->where('iddestino', '=', request('iddestino'));
             }
         }

      if (request()->has('idsetor')){
             if (request('idsetor') != ""){

                $destinos = $destinos->where('idsetor', '=', request('idsetor'));

             }
         }      
       // ordenando
       //  $destinos = $destinos->orderBy('destino', 'asc');

         $destinos = $destinos->paginate(session('perPage'))->appends([
             'servidors' => request('servidor'),
             'iddestino' => request('iddestino'),
             'idsetor' => request('idsetor'),
         ]);

         $perPages = PerPage::orderBy('valor')->pluck('nome', 'valor');

         $servidors = Servidor::orderBy('servidor')->pluck('servidor', 'idservidor');
         $setors = Setor::orderBy('setor')->pluck('setor', 'idsetor');


         return view('destino.index', compact('destinos','servidors', 'perPages', 'setors')); 
}

Error:

  

BadMethodCallException Method paginate does not exist.

    
asked by anonymous 31.10.2017 / 18:58

1 answer

2

It turns out that within this if

if (request()->has('servidor')){ }

You materialize the data with a ->get() . This causes the query to run in the database and the data is brought into memory.

Just remove this part, so:

if (request()->has('servidor')){
    if (request('servidor') != ""){
         $destinos = $destinos->join('servidors', 'destinos.idservidor', '=', 'servidors.idservidor')
            ->select('destinos.*', 'servidors.servidor')
            ->where('servidors.servidor', 'like', '%' . request('servidor') . '%');
    }
}
    
31.10.2017 / 19:18