Laravel, call additional method of the Model in Eloquent query

0

In my Deegre model I have a method fullName () that returns string

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Deegre extends Model
{

public function fullName(){

    $level = [
        "1" => "Primer ",
        "2" => "Segundo ",
        "3" => "Tercer ",
        "4" => "Cuarto ",
        "5" => "Quinto ",
        "6" => "Sexto ",
    ];
   return $this->code . $level[$this->type] . " Grado de Secundaria";
}

I want to call fullName () in my eloquent query

<?php

namespace App\Repositories;

use App\Deegre;

class DeegreRepository
{
 public function index(){
   return Deegre::where("year", now()->year)->get();
    // aqui quiero que mi metodo fullName sea llamado :(
 }

}

What I want is to call the method fullName that I have created in my query, so for each record that brings also bring me the value of my method, Thank you very much

    
asked by Elias Champi 27.12.2018 в 17:40
source

1 answer

0

What you are looking for is an Accessor, to format the value that the query delivers, for this you must use the Laravel convention that implies giving a name to the method starting with get and ending with Attribute :

public function getFullNameAttribute($value)
{
    $level = [
        "1" => "Primer ",
        "2" => "Segundo ",
        "3" => "Tercer ",
        "4" => "Cuarto ",
        "5" => "Quinto ",
        "6" => "Sexto ",
    ];
    return $this->code . $level[$this->type] . " Grado de Secundaria";
}

To use it you simply call it $result->full_name , after having made the query.

According to the information received later in the comments, to add the accessor to the answer json, we use appends in the model:

protected $appends = ['full_name'];
    
answered by 27.12.2018 / 18:00
source