laravel-admin

repository·master·Indexed 11 days ago

https://github.com/z-song/laravel-admin

An administrative interface builder for Laravel that enables developers to build CRUD backends with minimal code. It requires PHP >= 7.0.0 and Laravel >= 5.5.0. Features include a flexible content layout system using the Bootstrap grid, custom authentication provider support via Illuminate\Contracts\Auth\UserProvider, and a customizable navigation bar via Admin::navbar.

Tokens
26.8K
Snippets
99
Records
116
Agent score
95%

What's inside laravel-admin

  1. Understand the generated admin file structure

    master

    After running php artisan admin:install, the following directory structure is created for your administration logic:

    • app/Admin/routes.php: Used to define all admin-related routes.
    • app/Admin/bootstrap.php: The bootstrapper for laravel-admin. Use this file to register extensions, custom configurations, or other initialization logic (refer to comments within the file for usage examples).
    • app/Admin/Controllers/: The directory where all admin controllers are stored.
      • HomeController.php: Handles the initial request to the admin dashboard.
      • ExampleController.php: A sample controller provided for reference.

    Static front-end assets are located in /public/packages/admin.

    app/Admin
    ├── Controllers
    │   ├── ExampleController.php
    │   └── HomeController.php
    ├── bootstrap.php
    └── routes.php
  2. Display related data in a Grid

    master

    You can display data from related models using Eloquent relationship names. This works for One-to-One, One-to-Many, and Many-to-Many relationships.

    Syntax Options:

    1. Dot notation: $grid->column('relation.field');
    2. Relationship method: $grid->relation()->field();

    Relationship Types:

    • One-to-One: Access fields from the related model (e.g., profile.age).
    • One-to-Many: Access the collection of related models. You can use display() to count or format the related items (e.g., counting comments).
    • Many-to-Many: Access the collection of related models (e.g., roles). Use display() to iterate through the collection and format them (e.g., as labels).
    // One-to-One: Accessing profile age from User grid
    $grid->column('profile.age');
    // or
    $grid->profile()->age();
    
    // One-to-Many: Counting comments in a Post grid
    $grid->comments('Comments count')->display(function ($comments) {
        return count($comments);
    });
    
    // Many-to-Many: Displaying roles in a User grid
    $grid->roles()->display(function ($roles) {
        return join(' ', array_map(function ($role) {
            return "<span class='label label-success'>{$role['name']}</span>";
        }, $roles));
    });
  3. Handle One-to-One model relationships in forms

    master

    You can manage related models within a single form by using dot notation on the field names. This works provided your Eloquent models have the appropriate relationship methods defined (e.g., hasOne or belongsTo).

    For a User model that hasOne Profile, you can access profile fields using profile.field_name.

    // Assuming User has a profile() relationship
    Admin::form(User::class, function (Form $form) {
        $form->text('name');
        $form->text('email');
        
        // Accessing fields from the related Profile model
        $form->text('profile.age');
        $form->text('profile.gender');
    });
  4. Use the Bootstrap grid system for page layouts

    master

    laravel-admin utilizes the Bootstrap grid system, where each row is divided into 12 units. You can structure your content using row(), column(), and nested structures.

    Basic Row and Columns

    Use $content->row() to add a full-width line or a container for columns. Inside a row, use $row->column(size, content) where size is an integer from 1 to 12.

    Nesting Rows and Columns

    You can nest columns within columns, and rows within columns, to create complex layouts.

    • Column in a Column: Pass a closure to $row->column() to receive a Column object, then call $column->row() inside it.
    • Row in a Row: Pass a closure to $column->row() to receive a Row object, then call $row->column() inside it.
    // Example of nested columns and rows
    $content->row(function (Row $row) {
        $row->column(4, 'xxx');
    
        $row->column(8, function (Column $column) {
            $column->row('111');
            $column->row(function(Row $row) {
                $row->column(6, '444');
                $row->column(6, '555');
            });
        });
    });
  5. Configure request Parameters

    master

    You can set request parameters for your API calls within the api-tester interface. Supported parameter types include:

    • String: For standard text-based parameters.
    • File: For testing file uploads.

    Use this to test routes that rely on $request->all() or specific input values.

    // Example route to test parameter handling
    use Illuminate\Http\Request;
    
    Route::get('parameters', function (Request $request) {
        return $request->all();
    });
  6. Impersonate a user with 'Login as'

    master

    The Login as feature allows you to test authenticated API endpoints by specifying a specific User ID. When you enter a User ID in the Login as input field, the subsequent API request will be made as that user.

    This is useful for testing routes protected by middleware like auth:api.

    // Example of an authenticated route to test
    use Illuminate\Http\Request;
    
    Route::middleware('auth:api')->get('user', function (Request $request) {
        return $request->user();
    });
  7. Return error or success messages to the page

    master

    To provide feedback to the user after a form action, you can redirect back to the previous page using Laravel's back() helper combined with an Illuminate\Support\MessageBag. This allows you to pass structured title and message data to the session.

    use Illuminate\Support\MessageBag;
    
    // redirect back with an error message
    $form->saving(function ($form) {
        $error = new MessageBag([
            'title'   => 'title...',
            'message' => 'message....',
        ]);
    
        return back()->with(compact('error'));
    });
    
    // redirect back with a successful message
    $form->saving(function ($form) {
        $success = new MessageBag([
            'title'   => 'title...',
            'message' => 'message....',
        ]);
    
        return back()->with(compact('success'));
    });
  8. Add a Left Menu Item

    master

    You can manage the admin sidebar via the UI at http://localhost:8000/admin/auth/menu.

    When adding a menu link:

    • Internal Links: Enter the path part that does not include the /admin prefix. For example, if the full URL is http://localhost:8000/admin/demo/users, enter demo/users as the uri.
    • External Links: Enter the full URL (e.g., http://laravel-admin.org/).
  9. Generate a data model-based form

    master

    Use the Encore Admin orm method via the Admin facade to generate a form based on an Eloquent model. Inside the callback, use the Form instance to define various input fields that correspond to your database columns.

    Common field methods include:

    • $form->display('column', 'Label'): Displays a read-only value.
    • $form->text('column', 'Label'): Text input.
    • $form->textarea('column', 'Label'): Textarea.
    • $form->select('column', 'Label')->options($array): Dropdown selection.
    • $form->number('column', 'Label'): Numeric input.
    • $form->switch('column', 'Label'): Boolean switch.
    • $form->dateTime('column', 'Label'): Date and time picker.
    use App\Models\Movie;
    use Encore\Admin\Form;
    use Encore\Admin\Facades\Admin;
    
    Admin::form(Movie::class, function (Form $form) {
        $form->display('id', 'ID');
        $form->text('title', 'Movie title');
        
        $directors = [1 => 'John', 2 => 'Smith'];
        $form->select('director', 'Director')->options($directors);
        
        $form->textarea('describe', 'Describe');
        $form->number('rate', 'Rate');
        $form->switch('released', 'Released?');
        $form->dateTime('release_at', 'release time');
    });
  10. Add custom chart components to laravel-admin

    master

    Since version 1.5, laravel-admin no longer includes built-in chart components. To add charts, you must manually include a JavaScript library (like chartjs) and render it via a custom Blade view.

    Follow these steps:

    1. Download the library: Place the library files in your public directory (e.g., public/vendor/chartjs).
    2. Register the assets: Use Admin::js() in app/Admin/bootstrap.php to make the library available globally in the admin panel.
    3. Create a view: Create a Blade file containing the HTML <canvas> element and the <script> logic required by your chosen library.
    4. Render the view: Use $content->body(view('your.view.path')) within an admin controller to display the chart.
    // 1. In app/Admin/bootstrap.php
    use Encore	Admin\Facades\Admin;
    Admin::js('/vendor/chartjs/dist/Chart.min.js');
    
    // 2. In your Controller
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('Chart Overview');
            $content->body(view('admin.charts.bar'));
        });
    }