Skip to content
Advertisement

Laravel casts with relation

I’m making a survey website where users provide answers from 0 to 10. I was experimenting with the casts to store all questions and the answer in 1 row.

This is what the scores field looks like in the database

{"5":8,"6":8}

This is as expected. The “5” and “6” are ID’s of the question and the 8’s are the scores provided by the user.

I’m wondering if it’s possible to query the answers but include a relation to the question. I would like to see the results as follows

{"5" => {"question: ...", "answer: ..."}

So my question: is it possible to cast to an array but include relations in Laravel? Or will I need to loop the array and fetch the question data for each row.

Thank you!

Advertisement

Answer

You can do whatever you want with custom accessors and mutators, but I would not recommend storing the relation in the db. You don’t want references whole objects in there that might change independently, so keep it to ids and decorate your output after fetching scores from the db.

public function getScoresAttribute($value)
{
    // if using casts to array, this should already be done
    $scores = json_decode($value, true);

    $questions = Question::whereIn('id', array_keys($scores))->get();
    $rs = [];

    $questions->each(function($q) use ($rs, $scores) {
        $rs[$q->id] = [
            'question' => $q->toArray(),
            'answer'   => $scores[$q->id],
        ];
    });

    return $rs;
}

Now you can just do something like:

dd($survey->scores);

And you’ll get the decorated data.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement