Attempt to read property title on null Laravel
- 1
Hi,
I’m getting this error:
Attempt to read property [title] on null
This my relationship in my model:
public function ad_types()
{
return $this->belongsTo(AdType::class);
}
This is how I’m trying to output it in my blade view:
{{ $ad->ad_types->title }}
Here is my migration file:
Schema::create('ads', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 191)->unique();
$table->string('ad_url', 191);
$table->string('ad_img')->nullable();
$table->unsignedBigInteger('ad_type_id')->default(1);
$table->foreign('ad_type_id')->references('id')->on('ad_types');
$table->timestamps();
});
What am I doing wrong?
Thanks
Answers
- 1
You didn’t follow the naming convention of Laravel, which isn’t a problem, but in this case you need to specify your foreign key in your relationship like this:
public function ad_types(){
return $this->belongsTo(AdType::class, 'ad_type_id');
}
- 0
It happened to me as well. I had to change the order of my routes in web.php
It solved the issue, not sure, though, why.