kuchar kuchar - 5 months ago 36
SQL Question

Laravel: Display query with 10 random rows from mysql with paginate

I want to get from database 10 random rows and then display it on paginate.
One page should display only 1

row
and next button should display next
row
etc.
Also i have column that contains category id so for the first page i want to display row with
cat_id = 1
for third page i want to display row that have
cat_id = 3
.
Please tell me is it possible? I have no idea how to do it.

For now i have controller:

$rows=Row::all()->random(10)->paginate(1);


And it says that there is no
paginate
method :(

Answer

The all() method returns a Collection while paginate extends a Query Builder. So if you did not need any random results, you could call paginate directly like this

$rows=Row::paginate(1);

Now, the problem with random is that it works on a Collection so you cannot use it directly before calling paginate, so here I'm going to use orderByRaw('RAND()')

For e.g. to order the rows randomly and get only the first row with the cat_id the same as the current page number, you can do something like this,

$rows=Row::orderByRaw('RAND()')->groupBy('cat_id')->orderBy('cat_id', 'asc')->paginate(1);

I'm assuming that there are no gaps in cat_id here.

Comments