Laravel - How to page and give Order By

1

I have this code:

$modeloVideo = ModeloVideo::paginate(10);

I want to page by 10 and display order by desc (descending order).

How to do this query?

I tried this way:

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\ModeloVideo;

class HomeController extends Controller {

    public function home() {


        //TODOS OS REGISTROS DA TABELA
    $modeloVideo = ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

        $array = array("videos" => $modeloVideo,
        );

        return view('home',$array);
    }

Model code:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class ModeloVideo extends Model {
    //informando a tabela que sera usada
    protected $table = "modeloVideo";
    //quando fizer uma insercao ou update nao adicionar a coluna created ou update




}

?>

and has not yet worked, gives the error: BadMethodCallException Method orderBy does not exist.

    
asked by anonymous 19.12.2018 / 16:32

3 answers

1

To search with orderBy and paginate simply use the following syntax:

ModeloVideo::orderBy('created_at', 'desc')->paginate(10);

Just like this answer and this in SOen.

    
19.12.2018 / 19:26
1

Avoid doing so, just a few cases:

$modeloVideo = ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

Because, you're bringing in all() all the record in the database in a collection class and then there is an error because there is no orderBy in the collection command is sortBy and finally

paging creates a big bottleneck in your application. The% built for this command is: SQL .

Correct mode: first sorts values from the base and then paging all this already coming ready the data of your table, that is, SELECT * FROM modelo_video written by SQL framework , example :

$modeloVideo = ModeloVideo::orderBy('created_at', 'desc')->paginate(10);

and the Eloquent built for this command (basically speaking) is: SQL , and this data already comes the specified amount and that's the big difference. Note: This SELECT * FROM modelo_video ORDER BY created_at DESC limit 10 offset 0 is an example, the paginate method fetches information for page in several of SQL itself, this is even to exemplify the part of the bottleneck .

    
19.12.2018 / 19:26
-2

Before using orderBy you need to fetch the records in the database:

ModeloVideo::all()->orderBy('created_at', 'desc')->paginate(10);

->all() : searches all bank records

->orderBy : sorts the searched values

For pagination you will need to use the ->paginate method, see the example in official documentation

  

The error is caused because the orderBy method is not part of Model instances but collections .

    
19.12.2018 / 16:36