我爲用戶輕鬆開啓或關閉帖子製作自定義視圖。像這張圖片一樣。無法在Laravel中切換活動/非活動狀態行
我有這樣的錯誤:
POST http://127.0.0.1:8000/admin/apartments/1/active 404(未找到)。
在Controller/Admin/ApartmentController.php
:
public function index(Request $request)
{
$variations = Apartment::all();
$dataType = DataType::where('slug', '=', 'products')->first();
return view('voyager::apartments.browse', compact('dataType', 'variations'));
}
public function active(Apartment $apartment)
{
$apartment->active = true;
$apartment->save();
}
在resources/views/vendor/voyager/apartments/browse.blade.php
:
<tbody>
@foreach($variations as $data)
<tr>
<?php $checked = ($data->active == 1) ? true : false; ?>
<td>
<input type="checkbox" name="active" data-id="{{$data->id}}" class="toggleswitch toggleactive" @if($checked) checked @endif>
</td>
</tr>
@endforeach
</tbody>
@section('javascript')
<!-- DataTables -->
<script>
$(document).ready(function(){
$('.toggleswitch').bootstrapToggle();
});
function parseActionUrl(action, id) {
if (action.match(/\/[0-9]+$/)) {
return action.replace(/([0-9]+$)/, id);
}
return action + '/' + id;
}
$('.toggleactive').on('change', function() {
$.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(){
toastr.success("Updated success: apartment is actived");
});
});
</script>
@stop
...和routes/web.php
:
Route::group(['prefix' => 'admin'], function() {
Voyager::routes();
Route::post('apartments/:id/active', '[email protected]');
Route::group(['middleware' => ['admin.user'], 'as' => 'voyager.'], function() {
Route::resource('apartments', 'Admin\ApartmentController');
});
});
注:
如果我想單擊按鈕On
時顯示吐司消息,如:The apartment is enabled
。否則當點擊按鈕Off
時,它將顯示按鈕The apartment is disabled
。
有最好的方法來改變這段代碼?
$('.toggleactive').on('change', function() {
$.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(){
toastr.success("Updated success: apartment is actived");
});
});
運行'php artisan route:list'並檢查路由是否已註冊並在此處發佈結果。如果不是,那麼運行'php artisan route:clear'。 – Sandeesh