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

Asked

Viewed 422 times

4

Hello, I’m using Laravel 5.1 at the moment and I came up with a question. I have a grid that shows values of a given CRUD and 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 foreing_key, ie:

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 Laravel Mutators concept and through the print I did inside the method actually added what I wanted, but I can’t access the view or anywhere, and it doesn’t appear inside the object inside the controller. I am using the Mutators concept correctly or I will have to do a JOIN to solve this?

Example of the mutator:

getForeingKeyIdAttribute($value){
       $this->attributes['foreing_key_name'] = TableDaForeinkey::where('name','=', $value )->first()->name;
   }
  • Publish your models if possible. This helps to reproduce your question.

  • I don’t think it’s a good idea.

2 answers

3

You must create a $appends in his model (Eloquent) following an example given by the website Laravel.

Create an item within your model this way

protected $appends = ['is_admin'];

Now create your Access

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

Now you’ll get an extra field in your JSON or Array in a more transparent way and without altering the main data of your model.

Make sure you also put the $fillable that defines which elements refer to the table fields so you have no problem saving, changing and deleting items from that model

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

To take the most doubt see the link of Laravel itself: #Mass Assignment

  • That’s right. It was missing in my case only the $appends. So I was able to access it in the view.

1


Use the 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');
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.