Question

Is there a way to use an accessor to change a field for only a certain query in Laravel 4? So, I have a model, "Fanartist.php". In another table, "artists", I have the field "description". I am calling it with a join in a query function. This is the function:

public static function fan_likes_json() {
        $fan_likes = DB::table('fanartists')
                    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
                    ->where('fanartists.fan_id', '=', Auth::user()->id)
                    ->select('artists.id', 'artists.stage_name', 'artists.city', 'artists.state', 'artists.image_path', 'artists.description')
                    ->get();  

}

I am trying to change the "description" string for this specific query function, using something like this:

public function getDescriptionAttribute($value) {

        return substr($value, 0, 90);

    }

Do I add this to the Fanartist model, or the Artist model? And also, how do I have this accessor only affect the description field for this specific query function? I would like the description to remain unaltered for other purposes and queries. Thank you for your help.

Was it helpful?

Solution

I don't think Eloquent's accessors/mutators will help you for a custom query like the one you've specified. As an alternative, you could try something like this:

$fan_likes = DB::table('fanartists')
    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
    ->where('fanartists.fan_id', '=', Auth::user()->id)
    ->select(DB::raw('substring(artists.description, 1, 90) as description, artists.id, artists.stage_name, artists.city, artists.state, artists.image_path'))
    ->get();

Then, for the purpose of this query, the artist description will be the shortened version.

See: MySQL SUBSTRING and Raw expressions in Laravel 4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top