Heidel
454
2
Laravel

Laravel 5 show random post

Posted 2 years 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.

Controller

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]);
    }
}

routes

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.