Home > Enterprise >  Undefined variable $categories #Laravel
Undefined variable $categories #Laravel

Time:11-24

I have this controller

<?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]);
    }
}

and my blade is something like this(his call "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 >
        <div >
            <div >
                <h2>Categorias</h2>
                
                <hr>
                @foreach($categories as $cat)
                    <button>{{ $cat->CATEGORIA_NOME }}</button>
                @endforeach
            </div>
        </div>

the Model:

<?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');
    }
}

but i still receiving the error: Undefined variable $categories

I tried to using the

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

or

return view('home')->with('categories', $categories);

but it did not work

CodePudding user response:

Try using compact(), like this.

$categories = Category::all();

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

CodePudding user response:

try this :

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

if doesn't work try to dump your category model, see if the data is out or not

  • Related