Solve the problem that select in laravel admin cannot automatically select the current value when editing the form

Time:2021-10-25

For each model, you can create a method that can automatically generate the option of select.

For example, create a method to generate options for the model user. PHP

/**
     *Get user list - select option
     * @return User[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getSelectOptions()
    {
        $options = DB::table('users')->select('id','name as text')->get();
        $selectOption = [];
        foreach ($options as $option){
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }

Use it in the corresponding controller, such as the controller of article

protected function form()
    {
        return Admin::form(Article::class, function (Form $form) {

            $form->display('id', 'ID');

            $form - > text ('title ',' title ') - > rules ('required|min: 10');
            $form - > textarea ('description ',' summary introduction ');
            $form - > ueeditor ('body ',' body ') - > rules ('min: 10');
            $form - > select ('user_id ',' author ') - > Options (user:: getselectoptions());
            (omitted)

The interface method mentioned in the document and the format returned in the document cannot automatically select the original value, but can only be blank.
$form – > select (‘user_id ‘,’ author ‘) – > Options (admin_base_path (‘ / API / users’);