In Laravel 5.8, I have a custom attribute to recover the avatar via Gravatar. This is an attribute in the User model.
/**
* @return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
I have a belongsTo/hasMany relationship in the Post/User model.
Post model:
/**
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
User model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* @var string
*/
protected $table = 'users';
/**
* @var array
*/
protected $fillable = [
'username',
'email',
'password',
'api_token',
];
/**
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'api_token',
];
/**
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'admin' => 'boolean',
];
/**
* @return string
*/
public function getRouteKeyName()
{
return 'username';
}
/**
* @return HasMany
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
/**
* @return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
}
I pass the post by the URL of the route:
Route::get('post/{post}', 'BlogController@post');
I would like to retrieve the avatar attribute via post. Only, I recover a null. And I do not understand where it comes from.
public function post(Post $post)
{
dd($post->user); // user model without appends attributes
dd($post->user->avatar); // null
}