未定义的变量$categories #Laravel

9rnv2umw  于 2022-11-26  发布在  Go
关注(0)|答案(2)|浏览(135)

我有这个控制器

<?php

namespace App\Http\Controllers;

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

class CategoriesController extends Controller
{

    public function index()
    {
        $categories = Category::all();
        
        return view('home', ['categories'=> $categories]);
    }
}

而我的blade是这样的(他的调用“home.blade.php”)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/css/swiper.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/js/swiper.min.js"></script>
    <div class="container">
        <div class="row text-center mb-3">
            <div class="col-md-12">
                <h2>Categorias</h2>
                
                <hr>
                @foreach($categories as $cat)
                    <button>{{ $cat->CATEGORIA_NOME }}</button>
                @endforeach
            </div>
        </div>

型号:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['CATEGORIA_NOME', 'CATEGORIA_DESC'];
    protected $table = 'CATEGORIA';
    protected $primaryKey = 'CATEGORIA_ID';
    protected $timestamp = false;

    public function categorias()
    {
        return $this->hasMany(Product::class, 'CATEGORIA_ID');
    }
}

但我仍然收到错误:未定义的变量$categories
我试着用

$categories = Category::all();
    
    return view('home', ['categories'=> $categories]);


返回视图('home')-〉with('categories',$categories);
但没有成功

ipakzgxi

ipakzgxi1#

尝试使用compact(),如下所示。

$categories = Category::all();

return view('home', compact('categories'));
lf5gs5x2

lf5gs5x22#

试试这个:

return view('home', ['categories'=> Category::all()]);

如果不起作用,尝试转储您的类别模型,看看数据是否出来了

相关问题