Im new to lavarel, can you help me on this. I can’t seem to load the homepage after adding @foreach but if I remove it it seems to be fine and works normally.
Snippet from home.blade.php
@foreach ($products as $product)
<tr>
<td>{{ $product->name }}</td>
</tr>
@endforeach
The HomeController
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsProduct;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return IlluminateContractsSupportRenderable
*/
public function index()
{
$products = Product::all();
return view('home', compact('products'));
}
}
Model (Product.php)
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Product extends Model
{
use HasFactory;
protected $fillable = ['name'];
}
and for routing
<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('home');
});
Auth::routes();
Route::get('/home', [AppHttpControllersHomeController::class, 'index'])->name('home');
Can’t seem to get it working, I’m using chrome btw
Thanks!
Tried to remove the @foreach to just display
<p>{{ $product->name }}</p>
but it still has the same error on restart, tried
php artisan cache:clear
still didn’t work
2
Answers
i’m not eligable for commenting yet, so i’m writing here
btw, activating the error logs can be really helpful, laravel show the error in exact details and the cause
as you claimed that the page won’t be loaded only after writing the
foreach
, maybe checking the$products
and its type help.In your routes file, you have:
This route returns the home view directly without going through your HomeController. As a result, the
$products
variable is not being passed to the view, leading to the error you’re seeing.To fix this, update your root route to use the HomeController so that the products are fetched and passed to the view: