0

Why does the following hard coded eloquent query work:

Auth::user()->update(['text_only_email' => true ]);

But when the data comes via a form checkbox input it always updates as false even when the input is true ?

$data['text_only_email'] = $request->input('text_only_email', false);
Auth::user()->update($data);

See results from die and dump to prove the incoming value is true:

$data['text_only_email'] = $request->input('text_only_email', false);

dd($data);

Results of dump:

array:1 [▼
  "text_only_email" => "true"
]

* UPDATE *

I've added the following mutator to my User model to cast as boolean but it still doesnt work. Is my casting a string to boolean correct?

public function setTextOnlyEmailAttribute($value)
{
    $this->attributes['text_only_email'] = (bool)($value);
}

2 Answers 2

1

The value of test_only_email that you're getting in the request is a string, not a boolean. Convert it first to a boolean true/false value and then pass to update().

Sign up to request clarification or add additional context in comments.

1 Comment

I've added the following mutator to my user model to cast as boolean but it still doesnt work - see updated post.
0

Your mutator will always return true because "true" and "false" returns true when casted to boolean, both are strings with more than zero characters. You should do something like this:

public function setTextOnlyEmailAttribute($value)
{
    $this->attributes['text_only_email'] = $value == 'true' ? true : 
false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.