Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0
Solution

Modify your belongsTo to this: App\Models\User

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    protected $guarded = ['id', 'created_at'];

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

Take a look at belongsTo function. It initialize what you pass to it. In your case:
$instance = new $related;
$instance = new User;
Which is not what you want. :)

public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
	{
		// If no relation name was given, we will use this debug backtrace to extract
		// the calling method's name and use that as the relationship name as most
		// of the time this will be what we desire to use for the relationships.
		if (is_null($relation))
		{
			list(, $caller) = debug_backtrace(false, 2);

			$relation = $caller['function'];
		}

		// If no foreign key was supplied, we can use a backtrace to guess the proper
		// foreign key name by using the name of the relationship function, which
		// when combined with an "_id" should conventionally match the columns.
		if (is_null($foreignKey))
		{
			$foreignKey = snake_case($relation).'_id';
		}

		$instance = new $related;

		// Once we have the foreign key names, we'll just create a new Eloquent query
		// for the related models and returns the relationship instance which will
		// actually be responsible for retrieving and hydrating every relations.
		$query = $instance->newQuery();

		$otherKey = $otherKey ?: $instance->getKeyName();

		return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
	}
Last updated 9 years ago.
0

thx a lot it does the trick! :D

i didnt know i needed the path to the class... !

the tutorial is 4.2 so he doesn't use the namespace... !

but now it work great :D

0

Try

return $this->belongsTo(User::class);
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Korigoth korigoth Joined 9 Feb 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.