Open-Admin Documentation

website·Indexed 32 days ago

https://open-admin.org/docs

An administrative interface framework featuring Model-grid, Model-form, and Model-show components. It provides tools for access control, data export, form validation, and a variety of extensions including a log viewer, exception reporter, and task scheduling for Laravel.

Tokens
42.7K
Snippets
294
Records
311
Agent score
63%

What's inside Open-Admin

  1. Overview of open-admin for Laravel

    open-admin is an administrative interface builder for Laravel designed to help developers build CRUD backends quickly using minimal code.
  2. Overview of open-admin for Laravel

    open-admin is an administrative interface builder for Laravel that allows developers to build CRUD (Create, Read, Update, Delete) backends using a small amount of code.
  3. Implement a popup form for row actions

    You can create a popup form by implementing the form() method in your action class. The submitted data is then available in the handle() method via the Illuminate\Http\Request object.
    // Define the form fields
    public function form()
    {
        $this->addValues(false); // Disable filling from model
        $this->date('date', 'date');
        $this->checkbox('type', 'type')->options([1 => 'Advertising', 2 => 'Illegal']);
        $this->textarea('body', 'body')->rules('required');
    }
    
    // Handle the submitted form data
    use Illuminate\Http\Request;
    
    public function handle(Model $model, Request $request)
    {
        $model->date = $request->get('date');
        $model->type = $request->get('type');
        $model->body = $request->get('body');
        $model->save();
    
        return $this->response()->success('Success message.')->refresh();
    }
  4. Install an Open-Admin extension locally for development

    To develop an extension locally, add the extension path to the repositories section of your project's composer.json and then require the package. If the extension includes static assets, use the vendor:publish command to move them to the public directory.
    "repositories": [
        {
            "type": "path",
            "url": "app/Admin/extensions/open-admin-ext/phpinfo"
        }
    ]
    composer require open-admin-ext/phpinfo
    php artisan vendor:publish --provider=OpenAdmin\PHPInfo\PHPInfoServiceProvider
  5. Install the Open Admin Config extension

    The Open Admin Config extension allows you to store and manage configuration data in the database. Installation requires installing the package via Composer, running database migrations, and registering the configuration loader in the application service provider.
    # Install the package
    composer require open-admin-ext/config
    
    # Run migrations
    php artisan migrate
    
    # Import menus and permissions
    php artisan admin:import config
  6. Handle One-to-One relationships in forms

    To edit fields of a related model in a one-to-one relationship (HasOne or BelongsTo), use dot notation in the form field name. The relation function in the model must be lowercase (or will be converted to snake_case).
    // Model
    class User extends Model {
        public function profile() {
            return $this->hasOne(Profile::class);
        }
    }
    
    // Controller
    $form = new Form(new User);
    $form->text('name');
    $form->text('profile.age'); // Accesses the 'age' field on the related Profile model
    $form->text('profile.gender');
  7. Implement expandable column content

    The expand() method allows you to hide additional data that appears when the column is clicked. You can provide a callback that returns a component (like a Table) or a class implementing the Illuminate\Contracts\Support\Renderable interface for dynamic rendering.
    use OpenAdmin\Admin\Widgets\Table;
    
    // Using a callback to show a table of comments
    $grid->column('title', 'title')->expand(function ($model) {
        $comments = $model->comments()->take(10)->get()->map(function ($comment) {
            return $comment->only(['id', 'content', 'created_at']);
        });
        return new Table(['ID', 'content', 'release time'], $comments->toArray());
    });
    
    // Using a Renderable class
    $grid->column('title', 'title')->expand(\App\Admin\Extensions\Preview::class);
  8. Filter and modify Grid source data

    You can modify the underlying Eloquent query using $grid->model() to apply constraints, ordering, or limits. To add a search UI, use the filter($callback) method.
    // Modify query
    $grid->model()->where('id', '>', 100);
    $grid->model()->orderBy('id', 'desc');
    $grid->model()->take(100);
    
    // Add a search filter
    $grid->filter(function ($filter) {
        $filter->between('created_at', 'Created Time')->datetime();
    });
  9. Create cascading select fields

    Cascading selects allow a parent dropdown to trigger the loading of options for a child dropdown via the load method. The child field is populated based on the value of the parent.
    // Parent select: loads 'city' field from /api/city when value changes
    $form->select('province')->options(...)->load('city', '/api/city');
    
    // Child select
    $form->select('city');
    
    // Controller for /api/city
    public function city(Request $request)
    {
        $provinceId = $request->get('q');
        return Province::city()->where('province_id', $provinceId)->get(['id', DB::raw('name as text')]);
    }
  10. Implement multiple select filters in grid columns

    Create a checkbox-style filter for columns with a fixed set of options (e.g., status fields). Pass an associative array to the filter() method where keys are the database values and values are the human-readable labels.
    $grid->column('status')->filter([
        0 => 'Unknown',
        1 => 'Ordered',
        2 => 'Paid',
        3 => 'Cancelled',
    ]);
  11. Create a custom header tool for model-grid

    To add a custom tool (such as a filter button group) to the model-grid header, create a class that extends AbstractTool. You must implement a render() method to return the view and a script() method to handle the client-side behavior. The tool is then appended to the grid using the $grid->tools() method.
    // app/Admin/Extensions/Tools/UserGender.php
    namespace App\Admin\Extensions\Tools;
    
    use OpenAdmin\Admin\Admin;
    use OpenAdmin\Admin\Grid\Tools\AbstractTool;
    use Illuminate\Support\Facades\Request;
    
    class UserGender extends AbstractTool
    {
        protected function script()
        {
            $url = Request::fullUrlWithQuery(['gender' => '_gender_']);
            return <<<EOT
    document.querySelectorAll('.user-gender').forEach(el => {
        el.addEventListener('click',function () {
            var url = "$url".replace('_gender_', this.dataset.option);
            admin.ajax.navigate( url);
        })
    });
    EOT;
        }
    
        public function render()
        {
            Admin::script($this->script());
            $options = ['all' => 'All', 'm' => 'Male', 'f' => 'Female'];
            return view('admin.tools.gender', compact('options'));
        }
    }
    
    // In your Grid controller:
    use App\Admin\Extensions\Tools\UserGender;
    
    $grid->tools(function ($tools) {
        $tools->append(new UserGender());
    });
    
    if (in_array(Request::get('gender'), ['m', 'f'])) {
        $grid->model()->where('gender', Request::get('gender'));
    }

    // resources/views/admin/tools/gender.blade.php <div class="btn-group" data-toggle="buttons"> @foreach($options as $option => $label) <label class="btn btn-sm user-gender {{ \Request::get('gender', 'all') == $option ? 'btn-secondary' : 'btn-light' }}" data-option="{{$option}}"> {{$label}} </label> @endforeach </div>

  12. Implement a select dropdown with AJAX loading

    For large datasets, use the ajax method to load options dynamically from a controller endpoint. The API must return a JSON array of objects containing id and text keys.
    // Form definition
    $form->select('user_id')->options(function ($id) {
        $user = User::find($id);
        return $user ? [$user->id => $user->name] : [];
    })->ajax('/admin/api/users');
    
    // Controller method
    public function users(Request $request)
    {
        $query = $request->input("query");
        return User::where('name', 'like', "%$query%")->limit(10)->get(['id', 'name as text']);
    }
    
    // Expected JSON response:
    // [
    //     {"id":1,"text":"User 1"},
    //     {"id":2,"text":"User 2"}
    // ]