Attempt to read property title on null Laravel

Asked by: chris11
Date:
Viewed: 182
Answers: 2
  • 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

Answer by: jenniryan

Answered on: 25 Jan 2023 Marked as best by question author

  • 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');
}

Answer by: SarahM

Answered on: 25 Jan 2023

  • 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. 

Please log in to post an answer!