laravel 未定义变量$categorys时出错

bnl4lu3b  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(119)

我尝试从表类别中获取数据,并显示在前端Product.blade.php文件中,我得到了未定义的变量$categorys

Here my controller 
<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    //
    public function create(Request $request){
        $categorys = Category::all();
        $pro = new Product();
        $pro->productid = $request->productid;
        $pro->categoryid = $request->categoryid;
        $pro->name = $request->name;
        $pro->qty = $request->qty;
        $pro->price = $request->price;
        $pro->status = '1';
        $pro->save();
        return view('product')->with('categorys', $categorys);
    }
}
here my route
Route::post('/productcreate',[ProductController::class, 'create'])->name('createproduct');

Route::get('/product', function () {
    return view('product');
})->name('product');
here my frontend product.blade.php
<select class="form-select" aria-label="Default select example" name="categoryid">
   <option selected>Select CategoryName</option>
   @foreach ($categorys as $category)
      <option value={{$category->id}}>{{$category->name}}</option>
   @endforeach

</select>

我尝试在retun更改代码,但它不工作,请帮助我

6psbrbz9

6psbrbz91#

使用以下代码修改控制器和Route

控制器:

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function create(Request $request)
    {
        $categorys = Category::all();
        $pro = new Product();
        $pro->productid = $request->productid;
        $pro->categoryid = $request->categoryid;
        $pro->name = $request->name;
        $pro->qty = $request->qty;
        $pro->price = $request->price;
        $pro->status = '1';
        $pro->save();
        
        return redirect()->route('product')->with('categorys', $categorys);
    }
}

路线:

Route::post('/productcreate', [ProductController::class, 'create'])->name('createproduct');

Route::get('/product', function () {
    $categorys = Category::all();
    return view('product')->with('categorys', $categorys);
})->name('product');

希望它能起作用。

相关问题