Heidel's avatar

Laravel 5 get random post where is_approved = 1

I use code below to get and display random post

public function getRandomPost() {
        $post = Post::inRandomOrder()->first();
        return redirect()->route('posts.show', ["id" => $post->id]);
    }

but I need to get random post not from all but only from approved posts (where is_approved = 1) and not deleted (I use Soft Deleting). What is the best way to do that?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Just chain the condition ->where('approved', true) - soft deleting trait will take care of getting active posts already.

public function getRandomPost()
{
    $post = Post::inRandomOrder()
        ->where('approved', true)->first();
    return redirect()->route('posts.show', ["id" => $post->id]);
}
1 like

Please or to participate in this conversation.