Can I use several requests in a laravel 5.3 mutators?

2

I try to save two input in database and I was thinking about doing it with mutators, the fact is that if I modify a field I only manage that value because the $ value that I receive is the one that sends the request, but I need to use something so:

public function SetCedulaAttribute($value){
    //Se puede recibir un request? O un input que envia el controlador y que no esta en base de datos?
    $otroRequest = $request->nacion; 
    return $this->attributes['cedula'] = $otroRequest,'-'.$value;
}

How do I use an input in a mutator? Is it possible?

    
asked by Susje 06.04.2018 в 16:29
source

1 answer

3

It is not possible to use two values with a mutator, because it accepts only one value in its parameters, or at least it was not designed for that, although the values could be passed as an object, array, json or similar:

/**
 * Set a given attribute on the model.
 *
 * @param  string  $key
 * @param  mixed  $value
 * @return $this
 */
public function setAttribute($key, $value)
{
    // First we will check for the presence of a mutator for the set operation
    // which simply lets the developers tweak the attribute as it is set on
    // the model, such as "json_encoding" an listing of data for storage.
    if ($this->hasSetMutator($key)) {
        $method = 'set'.Str::studly($key).'Attribute';

        return $this->{$method}($value);
    }

    // If an attribute is listed as a "date", we'll convert it from a DateTime
    // instance into a form proper for storage on the database tables using
    // the connection grammar's date format. We will auto set the values.
    elseif ($value && $this->isDateAttribute($key)) {
        $value = $this->fromDateTime($value);
    }

    if ($this->isJsonCastable($key) && ! is_null($value)) {
        $value = $this->castAttributeAsJson($key, $value);
    }

    // If this attribute contains a JSON ->, we'll set the proper value in the
    // attribute's underlying array. This takes care of properly nesting an
    // attribute in the array's value in the case of deeply nested items.
    if (Str::contains($key, '->')) {
        return $this->fillJsonAttribute($key, $value);
    }

    $this->attributes[$key] = $value;

    return $this;
}

You could try playing with the facade Request to add the other value and put a default value (in case there is no such key in the Parameter bag), something similar to what you try:

$otroRequest = Request::get('nacion', 'ninguna');

return $this->attributes['cedula'] = $otroRequest,'-'.$value;
    
answered by 06.04.2018 / 17:01
source