Support the ongoing development of Laravel.io →
Database Eloquent

I want show related table columns (customers.name) in all select of model (User) laravel. I use accessor laravel.

user table:

id    name    customer_id
1     hassan  1

customer table:

id    name
1     customer1

now use

$user = Auth::user();
return $user;

I want show:

id: 1,
name: "hassan",
customer_id: {
    id: 1,
    name: "customer1"
}

but show this error:

Failed calling App\User::jsonSerialize()

my User Model.

class User extends Authenticatable
{
	use EntrustUserTrait;
	
	/**
	 * Get the user's customer name.
	 *
	 * @param  string $value
	 * @return array
	 */
	public function getCustomerIdAttribute($value)
	{
		return [
			'id' => $value,
			'name' => $this->customer->name
		];
	}
	
	/**
	 * The attributes that should be casted to native types.
	 *
	 * @var array
	 */
	protected $casts = [
		'customer_id' => 'array',
	];
	
	/**
	 * Get the customer record associated with the user.
	 */
	public function customer()
	{
		return $this->belongsTo(Customer::class);
	}
}

I do not want use below code, I want only change in model.

$user = Auth::user();
$user->customer;
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

HASSANDL hassandl Joined 30 Oct 2016

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.

© 2025 Laravel.io - All rights reserved.