Gaurav
Gaurav

Reputation: 149

Return Single column from HasOne laravel from model

I have the user image saved on a different table and I want to have the following in User model

public function Image()
{
    return $this->hasOne(UserImages::class, 'user_id', 'id')->latest();
}

The above relation returns the following.

"image": {
    "id": 3,
    "user_id": 1,
    "image": "http://live.test/uploads/user/User-Oss8MewXVzHZCehHoOUgkdYoo3N1K0gYI9jY69ZsnyiHnqHsHv.png",
    "is_primary": 1,
    "created_at": "2021-04-12T08:01:47.000000Z",
    "updated_at": "2021-04-12T08:01:47.000000Z"
},

I want to receive only image, how can I do that?

Upvotes: 0

Views: 2067

Answers (3)

Davy Baccaert
Davy Baccaert

Reputation: 31

You could use the magic Laravel provided:

$user->image->pluck('profile_image');

Documentation: https://laravel.com/docs/8.x/collections#method-pluck

Upvotes: 0

Akhtar Munir
Akhtar Munir

Reputation: 1769

You can create another function inside your model and access the previous method like

public function image()
{
  return $this->hasOne(UserImages::class, 'user_id', 'id')->latest();
}

public function avatar()
{
  return $this->image->image ?: null;
  //OR
  return $this->image->image ?? null;
  //OR
  return !is_null($this->image) ? $this->image->image : null;
  //OR
  return optional($this->image)->image;
}

And it will be accessible with $user->avatar();

As from discussion you are sending response to api

$this->user = $this->user->where('id', "!=", $current_user->id)->with(['chats','Image:user_id,image'])->paginate(50);

This will help you, but it will be better to use Resources for api responses to transform some specific fields.

Upvotes: 0

N69S
N69S

Reputation: 17205

use value() method

$user->image()->value('image');

From Eloquent documentation

If you don't need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:

$email = DB::table('users')->where('name', 'John')->value('email');

You can set it as a user attribute.

public function getProfileImageAttribute()
{
    return optional($this->image)->image;
    //or
    return $this->image->image ?? null; 
    //or
    return $this->image->image ?? 'path/of/default/image';
}

now you can call it like this

$user->profile_image;

Upvotes: 1

Related Questions