laravel-8 - 未捕获的错误:Ziggy 错误:路由“batch.run”不在路由列表中
问题描述
我已经设置了一个 Laravel8 博客演示应用程序来学习 Laravel8 的来龙去脉。然而,在创建一个新的控制器(PostsController 的副本称为 BatchesController)之后,将资源添加到 web.php,只有默认路由工作,例如编辑/创建/销毁。我尝试添加一条新路由,却得到以下错误:“未捕获的错误:Ziggy 错误:路由'batch.run'不在路由列表中”。
batch.run 是我的新路线,它几乎是已经设置用于删除帖子的“销毁”路线的副本。当我只是使用默认路由的近似副本时,我不明白我做错了什么。使用 web.php 中的所有“资源”时,这些路由在哪里“添加”。它不应该只是根据路由名称在控制器中运行任何方法吗?
这是我的 web.php:
Auth::routes(['verify' => true]);
Route::get('login', [LoginController::class, 'showLoginForm'])->name('showLoginForm')->middleware('guest');
Route::get('register', [RegisterController::class, 'showRegisterForm'])->name('showRegisterForm')->middleware('guest');
Route::post('login', [LoginController::class, 'authenticate'])->name('login');
Route::post('register', [RegisterController::class, 'register'])->name('register');
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
Route::resource('post', PostsController::class);
Route::resource('batch', BatchesController::class);
Route::resource('token', TokensController::class);
Route::resource('home', HomeController::class);
Route::redirect('/', 'home');
这是我的控制器方法:
public function run(Request $request, $id) {
Batch::find($id)->run();
$request->session()->flash('success', 'Batch run successfully!');
return redirect()->route('batch.running');
}
这是我的 .vue 文件(减去模板):
<script>
import AppHeader from "../../Partials/AppHeader";
import ErrorsAndMessages from "../../Partials/ErrorsAndMessages";
import {usePage} from "@inertiajs/inertia-vue3";
import {Inertia} from "@inertiajs/inertia";
import {computed, inject} from "vue";
export default {
name: "Batches",
components: {
ErrorsAndMessages,
AppHeader
},
props: {
errors: Object
},
setup() {
const route = inject('$route');
const deleteBatch = (id) => {
if (!confirm('Are you sure want to delete #' + id + '?')) return;
Inertia.delete(route('batch.destroy', {id}));
}
const runBatch = (id) => {
if (!confirm('Are you sure you want to run #' + id + '?')) return;
Inertia.post(route('batch.run', {id}));
}
const batches = computed(() => usePage().props.value.batches);
const numberLinks = batches.value.links.filter((v, i) => i > 0 && i < batches.value.links.length - 1);
return {
batches,
deleteBatch,
runBatch,
numberLinks
}
}
}
</script>
<style scoped>
.action-btn {
margin-left: 12px;
font-size: 13px;
}
.article {
margin-top: 20px;
}
</style>
解决方案
尝试为路线命名。
Route::get('gifts/list','GiftsController@list')->name("gifts.list");
并使用路由函数调用路由
let listUrl = route("gifts.list");
以上解决了我的问题。