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
Please remove $data from compact() function
return view('user.home',compact('data'));
You passed the variable $data to the view('user.home', compact('data')) but you have an error in the product.blade I think the problem is on the product. blade file. check that file
You error is in the product.blade.php view and in your controller you're returning the home.blade.php view.
You can avoid the Undefined variable error in your product.blade.php adding an isset in your view like this :
@if(isset($data))
@foreach($data as $product)
(...)
@endforeach
@endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With