Attempt to read property title on null Laravel

Asked by: chris11
Viewed: 419
Answers: 2
  • 1


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->string('title', 191)->unique();
$table->string('ad_url', 191);

What am I doing wrong?



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!