我使用相同的视图来显示一篇帖子和随机帖子
路线
Route::get('posts/{id}', 'PostsController@show')->name('posts.show');
Route::get('get-random-post', 'PostsController@getRandomPost');
PostsController中的方法
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
但现在我需要在两个视图之间添加一个小的差异。我怎样才能做到这一点?
UPD
我向 Controller 中的方法添加了变量 $randomPost
public function show($id) {
$randomPost = false;
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$randomPost = true;
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
并将下面的代码添加到
show
视图
@if($randomPost)
some text
@endif
但我不知道如何将变量从
getRandomPost()
传递到视图?
UPD2
结果我使用了会话,它有效,但我不确定方法
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
session()->flash('random_post', 'ok');
return redirect()->route('posts.show', ["id" => $post->id]);
}
查看
@extends('layouts.app')
@section('content')
<a href="{{ action('HomeController@index') }}">Home page</a>
<h2>#{{$post->id}}</h2>
{!! nl2br(e($post->text)) !!}
<?php if(session()->has('random_post')){
echo '<div style="text-align: center">';
echo link_to_action('PostsController@getRandomPost', 'Random Post', $parameters = array(), $attributes = array());
echo '</div>';
}?>
@stop
// set
session()->flash('random_post', 'ok');
// check
if(session()->has('random_post')){
// is random
getRandomPost
调用该函数。
public function show($id, $randomPost = false) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->where('is_published', 1)->first();
$this->show($post->id, true);
}