Search code examples
phplaraveldrop-down-menularavel-7laravel-admin

laravel-admin.org admin panel how to fetch users via dropdown menu and lookup users


I installed laravel-admin.org and then in admin panel my default form is this:

enter image description here

this is my Department Controller: in /admin/ folder:

I have methods

one for grid view:

/**
 * Make a grid builder.
 *
 * @return Grid
 */
protected function grid()
{
    $grid = new Grid(new Department());

    $grid->column('id', __('Id'));
    $grid->column('name', __('Name'));
    // $grid->column('owner_id', __('Owner id'));
    
    $grid->owner_id(__('models.name_of_user'))->display(function ($owner_id) {
        return ($owner_id ? User::find($owner_id)->name : null);
    });

    $grid->column('group_id', __('Group id'));
    $grid->column('limit', __('Limit'));
    $grid->column('created_at', __('Created at'));
    $grid->column('updated_at', __('Updated at'));

    return $grid;
}

one for detail view:

/**
 * Make a show builder.
 *
 * @param mixed $id
 * @return Show
 */
protected function detail($id)
{
    $show = new Show(Department::findOrFail($id));

    $show->field('id', __('Id'));
    $show->field('name', __('Name'));
    $show->field('owner_id', __('Owner id'));
    $show->field('group_id', __('Group id'));
    $show->field('limit', __('Limit'));
    $show->field('created_at', __('Created at'));
    $show->field('updated_at', __('Updated at'));

    return $show;
}

and one for form view for editing:

/**
 * Make a form builder.
 *
 * @return Form
 */
protected function form()
{
    $form = new Form(new Department());
    $form->text('name', __('Name'));
    $form->number('owner_id', __('Owner id'));
    $form->number('group_id', __('Group id'));
    $form->number('limit', __('Limit'));

    return $form;
}

How can I replace a dropdown menu to seek users from users model?

How can I search in that dropdownmenu so I can seek and filter my users by their emails?


Solution

  • enter image description here

    in your form :

        $form->select('owner_id', __('models.name_of_user'))->options(User::all()->pluck('name', 'id'));
    

    in your detail:

        $users = User::all()->toArray();
        $usersArray = [];
        foreach ($users as $item) {
            $usersArray[$item['id']] = $item['name'];
        }
        $show->owner_id(__('models.name_of_user'))->using($usersArray);
    

    in your grid:

        $grid->owner_id(__('models.name_of_user'))->display(function ($owner_id) {
            return ($owner_id ? User::find($owner_id)->name : null);
        });