Home > Net >  Undefined variable: data , $data is undefined. Laravel 8
Undefined variable: data , $data is undefined. Laravel 8

Time:11-20

I got an error says undefined variable data referring to my foreach in my blade

so my errors is : Undefined variable: data (View: C:\Users\adila\Desktop\onlineshop\onlineshop\resources\views\user\product.blade.php)

so this is my blade file :

<div class="latest-products">
      <div class="container">
        <div class="row">
          <div class="col-md-12">
            <div class="section-heading">
              <h2>Latest Products</h2>
              <a href="products.html">view all products <i class="fa fa-angle-right"></i></a>
            </div>
          </div>`enter code here`
         
          @foreach($data as $product)


          <div class="col-md-4">
            <div class="product-item">
              <a href="#"><img src="assets/images/product_06.jpg" alt=""></a>
              <div class="down-content">
                <a href="#"><h4>{{$product->title}}</h4></a>
                <h6>$ {{$product->harga}}</h6>
                <p>{{$product->deskripsi}}</p>
                
              </div>
            </div>
          </div>

        @endforeach

        </div>
      </div>
    </div>

and this is my controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Product;

class HomeController extends Controller
{
    public function redirect(){
        $usertype = Auth::user()->usertype;

        if($usertype=='1'){
            return view('admin.home');
        }

        else{
            return view('user.home');
        }
    }

    public function index(){


        if(Auth::id()){
            return redirect('redirect');
        }
        else{

            $data = Product::all();

            return view('user.home',compact('data', $data));
        }
        
    }
}

and my Route :

Route::get('/', [HomeController::class, 'index']);

Please help me

CodePudding user response:

Please remove $data from compact() function

     return view('user.home',compact('data'));

CodePudding user response:

i've tried both solutions in the aswer section . but it still error

  • Related