Monday, February 27, 2017

Laravel 5 get random post

There is a link "Get Random Story" <a href="#" class="btn-get-random-post">Get 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. 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 view('posts.show', compact('post'));
}
}

routes
Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('delete', 'PostsController@delete');
Route::post('get-random-post', 'PostsController@getRandomPost');

js
$(document).ready(function() { 
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('.btn-get-random-post').on('click', function(){

    $.ajax({
        type: 'post',
        url: './get-random-post',               
        error: function(jqXHR, textStatus, errorThrown) { 
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
    return false;
});

});

And I have 2 problems here
1. Method getRandomPost() returns post, but how to display it? I want to get as result page with url mysite/post/{id} like url from method show.
2. Is there any way to get and display random post (with url mysite/post/{id}) without AJAX?

UPD
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]);
}
}
link on the main page <a href="{{ action('PostsController@getRandomPost') }}">Random Story</a>
routes
Route::get('/', 'HomeController@index');

Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show')->name('posts.show');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('delete', 'PostsController@delete');
Route::post('get-random-post', 'PostsController@getRandomPost');
Route::post('dashboard/delete', 'PostsController@delete');
Route::post('dashboard/unpublish', 'PostsController@unpublish');
Route::post('dashboard/restore', 'PostsController@restore');

error:


via Heidel

Advertisement