A simple front-end component
I sometimes need to map the columns of eloquent models to fit the requirements of a front-end component. For example, I often have a "dropdown" component which expects an array of objects containing a value
and a text
key.
<template>
<select>
<option
v-for="option in optionsArray"
:value="option.value"
>{{option.text}}</option>
<select>
</template>
Transforming data
In order to fill this "generic" select component with data from the database we need to map one column to value
and another column to text
. This can be done client-side, however, I prefer to do this on the server since this feels like the right place to process data. The Laravel Collection class provides some nice methods to map the Eloquent models it contains. However, for the simple situation I'm describing here I like to do the mapping directly in the model's select()
statement.
// Select users as options for dropdown component
$usersAsOptions = User::select('id AS value, name AS text')->get();
Apart from having a sustinct line of code, this approach has some nice side effects:
- Only used columns are retrieved from the database;
- No additional processing in PHP is required to map the data;
- The JSON that's generated when outputting the data to the client only contains the selected columns;