Reputation: 13
I am trying to access my course information from a foreach, but it shows this error: Trying to get property of non-object.
I tried to access the information as follows: $purchase->course->name
also like this:
$ purchase[course][name]
but does not show any results, I have attached my model, my controller and my view.
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
protected $fillable = [
'transaction_id',
'user_id',
'course_id',
'status',
'total'
];
public function courses()
{
return $this->belongsTo(Course::class,'course_id');
}
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Purchase;
class PurchaseController extends Controller
{
public function index()
{
$purchases = Purchase::with('courses')->get();
return view('purchases.index',compact('purchases'));
}
}
View:
@foreach($purchases as $purchase )
{{$purchase->course->name}}
@endforeach
if show only the variable like this $purchase
all the data appears but when trying to access the course $purchase->course
it shows nothing.
In the controller it works fine only not works in blade view.
Upvotes: 0
Views: 612
Reputation: 3952
{{ $purchase->course->name }}
Should be:
{{ $purchase->courses->name }}
Your function name is courses() which means the attribute name is courses
, not course
.
Upvotes: 3