kuchar kuchar - 2 years ago 139
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

and next button should display next
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:


And it says that there is no
method :(

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download