John Davidson

php - Laravel Voyager Mutator


I'm having some issues using Voyager. I can create Accessors to attributes, as described in the documentation. It works nicely to access the data, but I also have to create a Mutator to change the data before saving it. Apparently, there's no implementation by Voyager, so I tried to do it through Laravel way. It also works very nicely in common environments, but for some reason, there is a different behavior with Voyager.

The Mutator is called after the Accessor, even when only browsing:


namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model

public function setNameAttribute($value){ // my mutator
$value = preg_replace("/[^a-zA-Z]/", '', $value);
$this->attributes['name'] = $value;
public function getNameBrowseAttribute(){ // my accessor
return $this->name . '...'; // example


What is happening:

When I access the browser of my Model, the getNameBrowseAttribute is called, as it should be, but after that, the setNameAttribute is called as well, which should not happen because I'm browsing, and not saving or updating the Model.

I tried to debug the code, and the last Voyager file called is a view, from voyager/storage/framework/views/, where $data is the Model:

if ($data->{$row->field.'_browse'}) {
$data->{$row->field} = $data->{$row->field.'_browse'}; // <-- this line

As you can see, it is calling a method with ...browse, and not set...

Any help is appreciated :)

My Answer:
This issue might be related to the order in which the mutators and accessors are being called in Voyager. In Laravel, mutators are typically called before accessors, so it's possible that Voyager is following a different order of execution.

One possible solution is to explicitly call the mutator before saving the data in your Voyager controller. You can do this by manually setting the attribute value using the mutator method before saving the model. Here's an example of how you can do this:

// In your Voyager controller
public function store(Request $request)
$data = $request->all();

// Call the mutator to modify the data before saving
$data['attribute_name'] = $this->mutateAttributeName($data['attribute_name']);

// Save the data

return redirect()->route('your.route');

// Mutator method in your model
public function mutateAttributeName($value)
// Modify the value here
return $modifiedValue;

By explicitly calling the mutator before saving the data, you can ensure that the data is modified correctly before being saved in Voyager. This should help you achieve the desired behavior in your application.

Rate this post

3 of 5 based on 3872 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us