skip to Main Content

I have this controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsCategory;

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 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>

the Model:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

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

2

Answers


  1. Try using compact(), like this.

    $categories = Category::all();
    
    return view('home', compact('categories'));
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search