Malvolio
Malvolio

Reputation: 366

Laravel How to properly handle values by id in an Eloquent Model

I have a Contact model like this

class Contact extends Eloquent
   {
   protected $table = "contacts";

   protected $position = array("frontend developer",
                               "light switch manager",
                               "product designer",
                               "head of tea kitchen");
   }

In my contacts table I want to store the contact's position using the $position array index as position-id, e.g.:

id     name               pos_id   email
--------------------------------------------------
1      George Teapotter   3        [email protected]

Now how would I effectively resolve the corresponding array string for the pos_id when querying the Contact model? I would need something like this in my query:

Contact::Select(name, **position(pos_id)**, email)->get();

to get as result for returning as json:

{ "George Teapotter", "head of tea kitchen", "[email protected]" }

Thanks for any hints.

Upvotes: 0

Views: 120

Answers (2)

Samuel Cloete
Samuel Cloete

Reputation: 332

The best would be to create another table in your DB for your position, as it means that you can then utilise Eloquent relations as well... There's hardly any performance overhead if you eager load your relation.

Upvotes: 1

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

you can do this easily with PHP, you don't need to do with mysql, your returned result is $rows so you can do this when you loop your result like this:

@foreach($rows as $row) 
<tr>
<td>{{$row->name}}</td>
<td>{{$position[$row->pos_id]}}</td>
<td>{{$row->email}}</td>
</tr>
@endforeach

if you want json encoded you can loop your result to do:

<?php 
foreach($rows as $row) {
    $row->pos_id = $position[$row->pos_id];
}
?>

Upvotes: 1

Related Questions