Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

php - How to bind string value from livewire frontend to property into integer casted?

I have a Livewire component, which binds an attribute named department_id directly inside the property model. The problem is, neither I define the model attribute cast department_id => integer or not defined, my Livewire component stores it as a string, not the integer when it received it from the frontend.

Below is the screenshot of the whole livewire component dumped by phpdebugbar.

capture from phpdebugbar

So my question is, How can I bind the string data from frontend directly inside model property, casted as integer?

<?php

namespace AppHttpLivewire;

use LivewireComponent;
use AppModelsUser;

class Form extends Component
{
    public User $user;

    protected $rules = [
        'user.department_id' => ['nullable', 'integer'],
    ];

    public function render()
    {
        return view('livewire.form');
    }

    public function save()
    {
        $this->validate();
        $this->user->save();
    }
}
<!-- /resources/views/livewire/form.blade.php -->
<select name="department-id" id="department-id" wire:model.lazy="user.department_id">
    <option value="1" {{ $user->department_id == 1 ? 'selected' : '' }}>Department #1</option>
    <option value="2" {{ $user->department_id == 2 ? 'selected' : '' }}>Department #2</option>
    <option value="3" {{ $user->department_id == 3 ? 'selected' : '' }}>Department #3</option>
</select>
question from:https://stackoverflow.com/questions/65859267/how-to-bind-string-value-from-livewire-frontend-to-property-into-integer-casted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can cast the property on the model, by setting the $casts property on your User model. Originally all data retrieved from a database is a string, you have to specifically cast it.

protected $casts = [
    'department_id' => 'integer',
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...