Accessor/Mutator do Laravel

Asked

Viewed 650 times

0

Replacement of "," by "." by Laravel Mutator Returns empty and unsaved in the database.

Productoscontroller

namespace App\Http\Controllers;

use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\ProdutoCreateRequest;
use App\Http\Requests\ProdutoUpdateRequest;
use App\Repositories\ProdutoRepository;
use App\Validators\ProdutoValidator;
use App\Services\ProdutoService;

class ProdutosController extends Controller
{
    protected $repository;

    protected $service;

    public function __construct(ProdutoRepository $repository, ProdutoService $service)
    {
        $this->repository   = $repository;
        $this->service      = $service;
    }

        public function store(ProdutoCreateRequest $request)
    {
        $request = $this->service->store($request->all());
        $produto = $request['success'] ? $request['data'] : null ;

        session()->flash('success', [
            'success'   => $request['success'],
            'messages'  => $request['messages'],
        ]);
        return redirect()->route('admin.produtos.create');
    }   
}

Productoservice

namespace App\Services;

use App\Repositories\ProdutoRepository;
use App\Validators\ProdutoValidator;
use Illuminate\Routing\Matching\ValidatorInterface;
use Exception;

class ProdutoService
{
    private $repository;
    private $validator;


    public function __construct(ProdutoRepository $repository, ProdutoValidator $validator)
    {
        $this->repository = $repository;
        $this->validator = $validator;
    }

    public function store($data)
    {
        try
        {
            $produto = $this->repository->create($data);
            return [
                'success'   => true,
                'messages'  => 'Produto cadastrado com Sucesso',
                'data'      => $produto,
            ];
        }
        catch(Exception $e)
        {
            dd($e);
            return [
                'success'   => false,
                'messages'  => 'Erro de execução',
            ];
        }
    }    
}

Product Model

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class Produto extends Model implements Transformable
{
    use TransformableTrait;
    use SoftDeletes;

    public $timestamps = true;

    protected $table = 'produtos';

    protected $fillable = [
        'titulo', 'status', 'console', 'genero', 'classificacao', 'custo', 'venda', 'desconto',
        'indatepromo', 'outdatepromo', 'quantidade', 'descricao', 'produtora', 'lancamento',
        'idioma', 'legenda', 'onplayers', 'offplayers', 'obs1', 'obs2', 'obs3', 'video',
    ];

    protected $hidden = ['status', 'custo'];

    /// CUSTO TROCA VIRGULA POR PONTO
    public function setCustoAttribute($value)
    {
        $this->attributes['custo'] = str_replace(",", ".", $value);
    }
    public function getCustoAttribute($value)
    {
        $this->attributes['custo'] = str_replace(".", ",", $value);
    }

    /// VENDA TROCA VIRGULA POR PONTO
    public function setVendaAttribute($value)
    {
        $this->attributes['venda'] = str_replace(",", ".", $value);
    }
    public function getVendaAttribute($value)
    {
        $this->attributes['venda'] = str_replace(".", ",", $value);
    }

    /// PROMOÇÃO TROCA VIRGULA POR PONTO
    public function setDescontoAttribute($value)
    {
        $this->attributes['desconto'] = str_replace(",", ".", $value);
    }
    public function getDescontoAttribute($value)
    {
        $this->attributes['desconto'] = str_replace(".", ",", $value);
    }
}

Produtorepository

namespace App\Repositories;

use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Interface ProdutoRepository.
 *
 * @package namespace App\Repositories;
 */
interface ProdutoRepository extends RepositoryInterface
{
    //
}
  • You should paste the code, not just use images

  • Please glue your controller and model I think I know what the problem is

  • @Jorgecosta Ready friend posted only the codes. posted also the service.

  • Please show the code for Productorepository $Repository in particular the create method.

  • @Jorgecosta I use the L5-Repository... I can only see it empty and the interface

  • @jorgeCosta and also when I send the data without the need to exchange the comma for points, the data is recorded normally

  • I think L5-Repository is your problem, you should not be respecting the mutators, you should do a simple test create a basic model without using L5-Repository put your mutators and use the create method directly in the template

  • @Jorgecosta With the Repository that I created worked correctly, it’s really the L5 that’s bugging you.. Now I need to figure out how to get this bagasse out of my basement,

  • Or I can continue with it, and only wear it on other occasions too.

  • Yes of course, please consider my answer as correct.

Show 5 more comments

1 answer

0


The implementation of Mutator (set) is correct

The implementation of Accessor (get) return a value

Replacing

public function getCustoAttribute($value)
    {
        $this->attributes['custo'] = str_replace(".", ",", $value);
    }

for

public function getCustoAttribute($value)
    {
       return  $this->attributes['custo'] = str_replace(".", ",", $value);
    }
  • Mano discovered the problem.. the error persisted in not having put "Return" in the Mutator there in the application Model.. after I put Return $this->Attributes['cost'] = str_replace(",", ".", $value); it worked fine now the//

  • But this is not the right way to create the mutator since it is a Setter

  • Corrected the answer given the correct designation Accessor

Browser other questions tagged

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