當我在 Laravel 中啟動該專案時,我有一個 ReturnController。但由於命名約定,我不得不將其重命名為 OrderController。我重新命名了控制器和模型,我運行所有php artisan cache:clear、php artisan route:cache、php artisan config:cache ...
等,但是當我嘗試在 中創建訂單時>views\orders\add.blade.php
(表單的操作是action="{{route('orders.store') }}"
)
我收到錯誤目標類別 [OrderController] 不存在。
這是web.php
內容:
Route::get('/', function () { return view('welcome'); }); Route::resource('customers', 'CustomerController'); Route::resource('orders', 'OrderController'); Auth::routes(); Route::get('/home', [App\Http\Controllers\OrderController::class, 'showOrders'])->name('orders'); Route::get('/orders/create', [App\Http\Controllers\OrderController::class, 'create'])->name('orders.create'); Route::get('/orders', [App\Http\Controllers\OrderController::class, 'index']);
我錯過了什麼?在使用正確的控制器名稱從頭開始重寫整個應用程式之前,如何解決此問題?
另一個線索是,為了導航到http://127.0.0.1:8000/home
,奇怪的是我必須新增行use App\Models\Order
在OrderController .php 中以便工作...所以這裡是OrderController.php 以幫助...
<?php namespace App\Http\Controllers; use App\Models\Order; use App\Models\Customer; use App\Models\Product; use Illuminate\Http\Request; class OrderController extends Controller { /** * Display a listing of the resource. */ public function index() { // } /** * Show the form for creating a new resource. */ public function create() { $customers = Customer::all(); $products = Product::all(); return view('orders.add', compact('customers', 'products')); } /** * Store a newly created resource in storage. */ public function store(Request $request) { // } /** * Display the specified resource. */ public function show(string $id) { // } /** * Show the form for editing the specified resource. */ public function edit(string $id) { // } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { // } /** * Remove the specified resource from storage. */ public function destroy(string $id) { // } public function showOrders() { $orders = Order::with(['customer', 'products'])->get(); return view('home', compact('orders')); } }
P粉5459565972024-01-17 14:58:06
在 web.php 中,而不是:
Route::resource('customers', 'CustomerController'); Route::resource('orders', 'OrderController');
用途:
Route::resource('customers', App\Http\Controllers\CustomerController::class); Route::resource('orders', App\Http\Controllers\OrderController::class);