Reputation: 137
I am trying to create a rule inside the user model, to check the user image is exist, and if it is exist return back the complete image url, I am doing this way but not working in foreach($users as $user) loop.
public function Image(){
$image = $this->user->image;
if(empty($image)){
$image = asset('images/profile/no-image.png');
}else{
$image = asset('images/profile/no-image.png');
}
return $image;
}
Upvotes: 1
Views: 9421
Reputation: 2463
What I do is store a default image in the database when te user is created. This is my migration. The table avatar has a default value default.png
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->string('password');
$table->string('avatar')->default('default.png');
$table->rememberToken();
$table->timestamps();
});
To get the image you simply call it like this
<img src="/image/location/{{ Auth::user()->avatar }}">
In a foreach loop you do something like this:
$users = User::all();
avatars = [];
foreach ($users as $key => $user){
$avatars[] = $user->avatar;
}
This returns an array of you avatars or in blade you do something like this:
@foreach($users as $user)
<img src="/image/location/{{ $user->avatar }}">
@endforeach
Upvotes: 0
Reputation: 1537
If you put the function on friend model then move it to your user model. Then make the function like this:
public function Image()
{
if ($this->image) {
return asset('images/profile/' . $this->image);
} else {
return asset('images/profile/no-image.png');
}
}
But i suggest you to use laravel Accessor:
public function getImageAttribute($value)
{
if ($value) {
return asset('images/profile/' . $value);
} else {
return asset('images/profile/no-image.png');
}
}
Then you can get image attribute through your model:
foreach($friends as $friend) {
{{ $friend->user->image }}
}
Upvotes: 7