1
votes
public function featuredimage()
{
    return $this->belongsTo(Image::class, 'featured_image_id')->withDefault();
}

this gives me: Call to undefined relationship [featuredimage] on model [App\Models\Core\Blog\Post].

any ideas why?

it should work according to docs:

https://laravel.com/docs/5.4/eloquent-relationships#updating-belongs-to-relationships

Default Models

The belongsTo relationship allows you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\User model if no user is attached to the post:

public function user()
{
    return $this->belongsTo('App\User')->withDefault();
}

my laravel version: 5.4.27

I have two tables:

posts table and images table

inside post table I do this:

$table->biginteger('featured_image_id')->nullable()->unsigned();

$table->foreign('featured_image_id')->references('id')->on('images')->onUpdate('cascade')->onDelete('cascade');
1
can you share your database design ? - Anar Bayramov
updated my question - niko craft
and your images table ? - Anar Bayramov
try this return $this->belongsTo(Image::class, 'featured_image_id', 'id')->withDefault(); - Anar Bayramov
Where do you place your image.php file? - Cong Chen

1 Answers

1
votes

I had the same issue. You need to upgrade to the latest laravel version as the withDefault method is available as from 5.4.28.

To update, simply run:

composer update