I would like to create an accessor on my user model that will return the first_name and last_name with space between them.
e.g. first_name = Sigal
last_name = Zahavi
$user->fullname should return Sigal Zahavi
From Laravel documentation :
use App\Support\Address;
use Illuminate\Database\Eloquent\Casts\Attribute;
/**
* Interact with the user's address.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function address(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => new Address(
$attributes['address_line_one'],
$attributes['address_line_two'],
),
);
}
I don't 100% understand it:
What is App\Support\Address?
What will the function return?
address_line_one and address_line_two of the address model with space in between?
My code:
In the User model:
protected function fullname(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => new User(
$attributes['first_name'],
$attributes['last_name'],
),
);
}
In my view:
<p>{{ Auth::user()->fullname }}</p>
And I get an error:
Illuminate\Database\Eloquent\Model::__construct(): Argument #1 ($attributes) must be of type array, string given, called in C:\wamp64\www\mysite\app\Models\User.php on line 163
I also tried, as a test, to do something on the UserAddr model:
protected function address(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => new UserAddr(
$attributes['addr_line_1'],
$attributes['addr_line_2'],
),
);
}
Then on a controller:
$addr = UserAddr::find(4);
dd($addr->address);
Getting the same error.
I don't understand the documentation.