Here is an example of displaying profile pics of list of users done in two different ways. I want to know what would be the good practice in terms of passing data to view. should I be looping the raw data in the controller method to fetch the image or do it while looping with in the view.
public function getProfilePicAttribute()
{
$profile_pic = config('app.USER_DEFAULT_PIC');
if( strlen(trim($this->pic))
&& \Storage::exists( config('app.USER_CDN_PATH').$this->pic )
){
return \Storage::url( config('app.USER_CDN_PATH').$this->pic );
}
// you could also return a default pic for people without profile picture
return false;
}
In your controller, stop using the toArray() on the collection.
public function controllerMethodHere(){
$users = User::where('status', 'A')->get();
return view('user.list', compact('users'));
}
It's really wasteful timewise/memorywise to retrieve results, loop over them and stick them in a new array... Might be fine for a few users, but imagine thousands, or more.
Using an accessor avoids all of that and just provides a clean and efficient way to get a property off the main object, even if that property doesn't originally exist in the result collection.
Arrays are fine really, but if you want less logic in your views, you're better off passing models and collections in there and having accessors / mutators with the logic in there.
toArray() will also introduce some overhead because it will go over all attributes, checking for mutators etc. even though a lot of those fields are not needed.