I
I
Ilya2018-06-01 15:00:02
Laravel
Ilya, 2018-06-01 15:00:02

How to set default value of model attribute in update process with fillable fields?

Greetings all
I can not find a solution to the problem.
In general, there is a field in the checkbox form with the name "published" and the value 1, if it is in the "checked" state, it is logical that the number 1 is sent to the controller update and this code works fine

public function update(Request $request, $id)
    {    
        $this->model->find($id)->update($request->all());

        return back();
    }

As soon as the checkbox is in the not checked state (they just didn't check the box), the update doesn't happen. In theory, this is normal, there is no checkmark - there is no "published" field in the Request object. The checkbox is on - we get the field in the request published = 1 and the update occurs.
The question is, is it possible to somehow update this field through the model! Important!
That is, we have the value of the checkbox = 1 - we update with one, we have nothing in the update process, - we set the default value of the model attribute published = 0. As soon as I did not try both through the "setPublishedAttribute" mutator and through protected $attributes - all in vain .
Of course, there are options to do it through Select with 1 or 0. radio, or check the request in the controller, but I would not want to put the save/create/update logic in the controller. Yes, and in the frontend there is an excellent built-in switch input in the form of a cool switch, but it is tied to the input checkbox unfortunately =(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yan-s, 2018-06-01
@flammerman

but I would not want to put the save/create/update logic into the controller

override update() of the model or add a separate method in it

P
pLavrenov, 2018-06-04
@pLavrenov

1) Instead of $request->all(), it's better to use $request->only(['required', 'fields', 'published'])
2) Mutators work only with data received from the database.
3) The simplest and most correct option is to specify the default value == 0 in the migration. Because the value can be either 0 or 1 and no other. And even if published data does not come from the frontend at all, save will work correctly without an error from PDO
$table->integer('published')->default(0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question