Correct use of Laravel Mutators 5.1. Is it possible to use in this way described below?

3

Hello, I'm using Laravel 5.1 at the moment and I had a question. I have a grid that shows values of a certain CRUD and in it I search through Table :: all (), which returns something like:

array:5 [▼  
"primary_key_id" => 1,
"foreing_key_id" => 5,
"name" => "testes",
"created_at" => "2015-10-05 21:25:27",
"updated_at" => "2015-10-05 21:25:27"

I would like to add in this object the name of the foreing_key, that is:

array:6 [▼  
"primary_key_id" => 1,
"foreing_key_id" => 5,
"name" => "testes",
"created_at" => "2015-10-05 21:25:27",
"updated_at" => "2015-10-05 21:25:27",
**"foreing_key_name = "Teste"**

I tried to use the concept of Mutators of Laravel and through the print I made within the method actually added what I wanted, but I can not access the view and nowhere, and does not appear inside the object inside the controller. Am I using the Mutators concept correctly or am I going to have to do a JOIN to solve this?

Mutator example:

getForeingKeyIdAttribute($value){
       $this->attributes['foreing_key_name'] = TableDaForeinkey::where('name','=', $value )->first()->name;
   }
    
asked by anonymous 06.10.2015 / 16:09

2 answers

1

Use with to bring the related model:

Tabela::with('relationMethod')->get();

app / Table.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class tabela extends Model
{
    public function relationMethod()
    {
        return $this->hasMany('App\RelationModel');
    }
}
    
06.10.2015 / 19:58
2

You should create a $appends in your model (Eloquent) following an example given by the site Laravel.

Create an item within your model in this way

protected $appends = ['is_admin'];

Now create your Accessor

public function getIsAdminAttribute()
{
    return $this->attributes['admin'] == 'yes';
}

Now you will receive one more field in your JSON or Array more transparently and without changing the main data of your model .

Make sure you also set the $fillable which defines which elements are referring to the table fields so that you have no problem at the time of writing, changing, and deleting items from that table

protected $fillable = ['first_name', 'last_name', 'email'];

To get the most doubt see Laravel's own link: #Mass Assignment

    
06.10.2015 / 17:34