简单发布/取消发布按钮应使用0
/ 1
更新提交时的数据库表列。
有两个按钮:
{!! Form::open(array('route' => array('book.publish', $book->id), 'method' => 'post')) !!}
<button class='btn btn-default'>Publish</button>
{!! Form::close() !!}
{!! Form::open(array('route' => array('book.publish', $book->id), 'method' => 'post')) !!}
<button class='btn btn-danger'>Unpublish</button>
{!! Form::close() !!}
两条路线
Route::post('book/publish/{publish}', 'BookController@publish')->name('book.publish');
Route::post('book/unpublish/{unpublish}', 'BookController@unpublish')->name('book.publish');
和控制器
public function publish($id){
$publish = Books::find($id);
$publish->published = 1;
$publish->save();
return redirect()->route('book');
}
public function unpublish($id){
$publish = Books::find($id);
$publish->published = 0;
$publish->save();
return redirect()->route('book');
}
有人可以帮我把它写成一个函数吗?目标是只显示一个按钮,具体取决于该书的状态。如果在数据库中发布,则按钮应显示未发布且相反的方式。
答案 0 :(得分:3)
<强>控制器强>
@if($book->published === 1)
// Show button to unpublish
@else
// Show button to publish
@endif
查看强>
Route::post('book/publish/{publish}', 'BookController@togglePublish')->name('book.publish');
<强>路线强>
if ($publish->published === 1)
注意强>
在控制器和视图中:
if ($publish->published)
与
完全相同{{1}}
但我认为明确地写它会更清楚。
答案 1 :(得分:1)
控制器:
public function publish($id, $status){
$publish = Books::find($id);
$publish->published = $status;
$publish->save();
return redirect()->route('book');
}
路线:
Route::post('book/publish/{publish}/{status}', 'BookController@publish')->name('book.publish');
模板:
{!! Form::open(array('route' => array('book.publish', $book->id, 1), 'method' => 'post')) !!}
<button class='btn btn-default'>Publish</button>
{!! Form::close() !!}
{!! Form::open(array('route' => array('book.publish', $book->id, 0), 'method' => 'post')) !!}
<button class='btn btn-danger'>Unpublish</button>
{!! Form::close() !!}
答案 2 :(得分:1)
如果您只想更改状态,可以使用三元运算符:
$publish->published = $publish->published == 1 ? 0 : 1;
或者你可以试试这个:
$publish->published = !$publish->published;
答案 3 :(得分:1)
只需将您的观点更改为:
@if($book->published === 1)
{!! Form::open(array('route' => array('book.publish', $book->id), 'method' => 'post')) !!}
<button class='btn btn-default'>Publish</button>
@else
{!! Form::open(array('route' => array('book.unpublish', $book->id), 'method' => 'post')) !!}
<button class='btn btn-danger'>Unpublish</button>
@endif
{!! Form::close() !!}
路线:
Route::post('book/publish/{publish}', 'BookController@publish')->name('book.publish');
Route::post('book/unpublish/{unpublish}', 'BookController@unpublish')->name('book.unpublish');
控制器:
public function publish($id){
Books::where('id', $id)->update(['published' => 1]);
return redirect()->route('book');
}
public function unpublish($id){
Books::where('id', $id)->update(['published' => 0]);
return redirect()->route('book');
}
为什么这个答案比发布的其他答案好?