Tahmina Akter
Tahmina Akter

Reputation: 53

Laravel Eloquent accessor : modify value by request parameter

I would like to add a prefix in username column which is directly coming from HTTP request. My controller function is like below:

    public function myFunc(Request $request){
        $prefix = $request->get("prefix");
        $users = User::all(); //need to change
    }

My User Model :

    public function getFullNameAttribute()
    {
        $full_name = $this->name . ' (' . $this->company_name . ')';
        return $full_name;
    }

How can I pass the $prefix in my accessor?

    public function getFullNameAttribute()
    {
        $full_name = $prefix."- ".$this->name . ' (' . $this->company_name . ')';
        return $full_name;
    }

Upvotes: 5

Views: 2029

Answers (3)

Wcan
Wcan

Reputation: 878

Lumen: 5.6.*:

For future reference in case if anyone is wondering how to resolve the current request from the Service Container in accessor.

$requestParameter = app('Illuminate\Http\Request')->get('request_parameter_goes_here');

Upvotes: 0

mrhn
mrhn

Reputation: 18936

You can resolve the request in the accessor. Setting a default string if you string is sent.

public function getFullNameAttribute()
{
    $request = resolve(Request::class);
    $prefix = $request->get('prefix', '');

    return $prefix."- ".$this->name . ' (' . $this->company_name . ')';
}

Upvotes: 5

Muhammad Dyas Yaskur
Muhammad Dyas Yaskur

Reputation: 8118

you can do it using foreach on the eloquent collection in your controller:

public function myFunc(Request $request)
{
    $prefix = $request->get("prefix");
    $users  = User::all(); //need to change
    foreach ($users as $user) {
        $user->full_name = $prefix."- ".$user->full_name;
    }
}

or you can do it using request() function in your model:

public function getFullNameAttribute()
{    
    return request()->prefix."- ".$this->name . ' (' . $this->company_name . ')';
}

But I think it's better using conditional like below:

public function getFullNameAttribute()
{
    if (request()->prefix) {
        return request()->prefix."- ".$this->name.' ('.$this->company_name.')';
    } else {
        return $this->name.' ('.$this->company_name.')';
    }
}

Upvotes: 2

Related Questions