My issue with laravel is that any data that I want to show returns a model instead of the data.
I migrated my database 4 times just to check if it wasn't an error inside the database, tinker returns models aswell.
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$products = Product::get();
dd($products);
return view('home');
}
}
My model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'Product_name',
'Product_image',
'Product_price',
'Store_ID'
];
}
My blade
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
{{ __('You are logged in!') }}
</div>
</div>
</div>
</div>
</div>
@endsection
Product::get();
returns the following:
I have searched everywhere and I somehow cannot find anybody with the same error. What am I doing wrong?
CodePudding user response:
The returning of a Collection is the expected behaviour for retrieving multiple models. Just loop through them in your blade file as you would if it were an array:
public function index()
{
$products = Product::get();
return view('home', compact('products'));
}
@extends('layouts.app')
@section('content')
<div class="container">
<ul>
@foreach($products as $product)
<li>{{ $product->Product_name }} - {{ $product->Product_price }}</li>
@endforeach
</ul>
</div>
@endsection
When you use dd()
you'll see the actual model class. The models are designs so that you can access the row data from them directly, though e.g. $product->Product_name
.