Laravel 5 show random post

Posted 1 year ago by Heidel

There is a link "Random Story" <a href="{{ action('[email protected]') }}">Random Story</a> on the main page of my site, on click I need to get random post from DB and show it on the same window with url sitename/post/{id}. I use Laravel 5.4.


class PostsController extends Controller
    public function index() {
        return redirect('/');

    public function show($id) {
        $post = Post::findOrFail($id);
        return view('posts.show', compact('post'));

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


Route::get('/', '[email protected]');

Route::get('posts', '[email protected]');
Route::get('posts/create', '[email protected]');
Route::get('posts/{id}', '[email protected]')->name('posts.show');
Route::post('posts', '[email protected]');
Route::post('publish', '[email protected]');
Route::post('delete', '[email protected]');
Route::post('get-random-post', '[email protected]');
Route::post('dashboard/delete', '[email protected]');
Route::post('dashboard/unpublish', '[email protected]');
Route::post('dashboard/restore', '[email protected]');

but when I click on the link a, I get an error and redirect doesn't work

MethodNotAllowedHttpException in RouteCollection.php line 233:

What am I doing wrong?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.