[Proposal] Create a random() method for Eloquent
There is currently no convenient way to do a ORDER BY RANDOM() query in Laravel. The current workaround is to write something like User::orderByRaw("RAND()")->get();. We could add a new method random() to wrap that functionality. Additionally the correct strings should be added to the grammar files.
- MySQL uses ORDER BY RAND()
- PostgreSQL uses ORDER BY RANDOM()
- SQLite uses ORDER BY RANDOM()
- SQL Server users ORDER BY NEWID()
The function could look like this:
public function random()
{
return $this->orderByRaw($this->grammar->compileRandom());
}
:+1:
:+1:
:+1:
@taylorotwell Should I make a pull request?
:+1:
There is some concern over the performance of ORDER BY RAND() (at least with MySQL) but it should be up to the developer to decide if it's the right solution for their application IMO.
:thumbsup:
If there are no additional remarks concerning my local changes, I could make a PR.
:thumbsup:
:+1: , can come quite handy when you need to display list of randomly sorted featured products for example.
As noted in the (closed) PR above, you can use shuffle(), but that hydrates all the items from the table, if you just want x random items. Also makes it a bit easier to abstract between different database, even if it isn't super efficient to get random items in MySQL this way.
Feel free to send a pull. You didn't really need to create a proposal for something this quick to implement. Proposals are only design to prevent people wasting hours writing something we don't want.
@GrahamCampbell as PR was created in https://github.com/laravel/framework/pull/5435 but was rejected.
@barryvdh Thanks for letting me know. :)
Well yeah, but if you look at this + the related issue, you'll see that there is an interest for this (relative) simple function, but there is some confusion over the usefulness. Would be nice if that would get looked after again..
I don't really see the uses here? It sounds like a good idea on the surface, but I don't think many people would actually use this.
Well, at least these 10 people who favorited this ;)
Yeh, but as I said, there's one thing favouring something, but it's another actually using it.
So how do you want to measure if people are going to use something that doesn't exist yet? I use the random function already, by using a raw order. But as stated, that doesn't work when switching databases..
Ok. Well at the end of the day, I don't decide what makes it into the framework. Only Taylor does, and he closed the pull request to add it. Not much more I can do really.
Currently, to have this much needed method, I have to add 3 files of voodoo core extension, extending DatabaseManager and Query\Builder, whereas it would be so simple, and helpful for people, just to merge the linked tiny PR.
Please, as a Christmas gift?