### Configure Database Connection in .env Source: https://github.com/owl-admin/docs/blob/master/docs/guide/index.md This snippet shows the essential database configuration variables in the `.env` file for a MySQL connection. Users should update these values to match their local database setup. ```dotenv DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=owl_admin DB_USERNAME=root DB_PASSWORD= ``` -------------------------------- ### Publish and Install Owl Admin Assets Source: https://github.com/owl-admin/docs/blob/master/docs/guide/index.md These Artisan commands are crucial for setting up Owl Admin. `admin:publish` publishes necessary framework resources, and `admin:install` completes the installation process, which may include database migrations and initial configurations. ```shell # 先发布框架资源 php artisan admin:publish # 执行安装 (可以在执行安装命令前在 config/admin.php 中修改部分配置) php artisan admin:install ``` -------------------------------- ### Create New Laravel Project Source: https://github.com/owl-admin/docs/blob/master/docs/guide/index.md This command initializes a new Laravel project named 'example-app' using Composer, the PHP dependency manager. It sets up the basic Laravel application structure. ```shell composer create-project laravel/laravel example-app ``` -------------------------------- ### Install Owl Admin Composer Package Source: https://github.com/owl-admin/docs/blob/master/docs/guide/index.md This Composer command adds the `slowlyo/owl-admin` package as a dependency to your Laravel project, downloading it from Packagist. ```shell composer require slowlyo/owl-admin ``` -------------------------------- ### PHP Usage Example for Custom `Components` Class Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/component-encapsulation.md This PHP example illustrates how to instantiate and utilize methods from the custom `Components` class. It demonstrates calling the `jumpToBaiDu` method to render the encapsulated UI action. Furthermore, it shows how to chain additional methods, such as `className('btn btn-primary')`, to apply styling or other modifications to the returned component, highlighting the flexibility of the encapsulated design. ```php Components::make()->jumpToBaiDu(); // 你依然可以继续调用组件的方法 Components::make()->jumpToBaiDu()->className('btn btn-primary'); ``` -------------------------------- ### PHP Watermark Component Usage Example Source: https://github.com/owl-admin/docs/blob/master/docs/guide/extension-component/watermark.md Demonstrates how to use the Watermark component in PHP, setting various properties such as width, height, rotation, z-index, content text, font style, and gap between watermarks. This example wraps a TextControl within the watermark. ```php amis()->Watermark()->body( // 水印包裹的内容 amis()->TextControl() ) ->width(100) // 设置宽度 (一般不需要) ->height(200) // 设置高度 (一般不需要) ->className('p-5') // eg: 添加内边距 ->rotate(90) // 设置旋转角度 ->zIndex(999) // 设置 z-index // ->image(config('admin.logo')) // 可以设置图片 ->content('Owl Admin') // 设置水印的文字内容 ->font([ // 文字样式 'color' => 'red' ]) ->gap([100, 100]) // 设置水印之间的间距 ; ``` -------------------------------- ### PHP `Components` Class Definition for Custom UI Actions Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/component-encapsulation.md This PHP code defines the `Components` class within the `App\Support` namespace, serving as a container for custom UI elements. It includes a static `make` method for fluent instantiation and an example `jumpToBaiDu` method. The `jumpToBaiDu` method returns an `amis` URL action, configured to open a link to Baidu in a new tab, demonstrating how to encapsulate specific UI behaviors. ```php UrlAction()->url('https://www.baidu.com')->type('link')->blank()->label('百度一下'); } } ``` -------------------------------- ### Get Full Admin Resource Path Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Returns the complete, absolute path for an administrative resource. This is useful for linking to assets or files within the admin context. ```APIDOC admin_resource_full_path(string $path):string ``` -------------------------------- ### Generate Admin URL Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Generates an administrative URL. It allows specifying a path and an optional boolean flag to include a prefix (e.g., '/admin-api/'). Examples demonstrate how to generate URLs with and without the prefix. ```APIDOC admin_url($path = null, $needPrefix = false):string ``` ```php // eg: admin_url('user'); // /user admin_url('user', true); // /admin-api/user ``` -------------------------------- ### Get Admin Directory Path Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Returns the base path to the admin directory. An optional sub-path can be provided to get a specific path within the admin directory. ```APIDOC admin_path(string $path = null):string ``` -------------------------------- ### Build Edit Form with `form` Method Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/update.md This snippet demonstrates the `form` method used to construct an editable form. It explains how the frontend (amis) interprets the returned structure to build the form, whether in page mode or modal mode. The `baseForm()` method handles basic form content, and the example shows adding `TextControl` fields for 'name' and 'email'. ```php /** * 前端 amis 通过识别 form 方法返回的结构来构建表单 * * @param bool $isEdit 用于判断是否为编辑 * * @return Form */ public function form($isEdit) { // baseForm 方法中, 处理了表单的一些基础内容 // 可以传入一个 bool 参数, 控制在表单提交成功后是否返回上一页 return $this->baseForm()->body([ TextControl::make()->name('name')->label('Name'), TextControl::make()->name('email')->label('Email'), ]); } ``` -------------------------------- ### Get Current Admin User Information Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Retrieves information about the currently logged-in administrative user. This allows access to user properties such as their ID. ```php $userId = admin_user()->id; ``` -------------------------------- ### Handle CRUD Index Requests in PHP Controller Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `index` method in the controller efficiently handles multiple types of GET requests based on the `_action` parameter. It can query and return a data list, process data export requests, or return the Amis list page structure for the frontend. This design minimizes routing complexity by consolidating CRUD operations. ```php public function index() { // 带有参数 ?_action=getData 的请求, 查询数据并返回 if ($this->actionOfGetData()) { return $this->response()->success($this->service->list()); } // 带有参数 ?_action=export 的请求, 处理导出 if ($this->actionOfExport()) { return $this->export(); } // 没有携带 _action 参数的请求, 返回列表结构 return $this->response()->success($this->list()); // 这里调用了 list 方法 } ``` -------------------------------- ### Get Database Table Columns Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Retrieves the column names for a specified database table. This function is useful for dynamic form generation or data validation based on table schema. ```APIDOC table_columns(string $table):array ``` -------------------------------- ### PHP Amis Form Dynamic Select Options Source: https://github.com/owl-admin/docs/blob/master/docs/faq/php-amis.md This example demonstrates how to correctly implement dynamic select options in an Amis form using PHP in OwlAdmin. It highlights that direct PHP variable interpolation (e.g., `${type}`) within `options` does not work for dynamic data because the value passed to the `getOptions` method is a literal string, not the dynamic field value. The correct method involves using an API endpoint (`/get_options?type=${type}`) to fetch options dynamically based on other form fields. ```php // eg: 根据 type 的值, 动态切换 options 的选项数据 public function form() { return $this->baseForm()->body([ amisMake()->SelectControl()->name('type')->label('类型')->options([ 'a' => 'A', 'b' => 'B', 'c' => 'C', ]), // 在执行到 getOptinos 方法时, 传入的只是一个字符串, 并不是 type 的值 amisMake()->SelectControl() ->name('options') ->label('对应选项') ->options(DataModel::getOptions('${type}')), // 正确做法 amisMake()->SelectControl() ->name('options') ->label('对应选项') ->api('/get_options?type=${type}') // 通过 api 动态获取选项 ]); } ``` -------------------------------- ### Simplify Amis Component Creation with amisMake Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Addresses the issue of excessive 'use' statements in complex pages by providing a simplified way to create Amis components. This helper allows for direct instantiation of components like `TextControl` without explicit class imports. ```php amisMake()->TextControl()->name('name')->label('label'); // 等效于 TextControl::make()->name('name')->label('label'); ``` -------------------------------- ### Create Basic Page with Slowlyo\SlowAdmin\Renderers\Page Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Demonstrates how to instantiate a new page object using the `Slowlyo\SlowAdmin\Renderers\Page::make()` method and return it as a successful response. This is the fundamental step for creating a new page in the `owl-admin` framework. ```php $page = \Slowlyo\SlowAdmin\Renderers\Page::make(); return $this->response()->success($page); ``` -------------------------------- ### Access Admin Settings Service Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Provides access to the `AdminSettingService` instance, allowing interaction with application settings. ```APIDOC settings():\Slowlyo\OwlAdmin\Services\AdminSettingService; ``` -------------------------------- ### Create Generic Components or Use Amis Helper in owl-admin Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Provides alternative ways to create components when a specific renderer class is not directly available or for more generic component creation. It shows using `Slowlyo\SlowAdmin\Renderers\Component::make()` with `setType()`, the `amis()` helper function, and notes a less recommended direct array approach. ```php \Slowlyo\SlowAdmin\Renderers\Component::make()->setType('page')->title('我是标题'); // 或者 amis('page')->title('我是标题'); // 等效于 \Slowlyo\SlowAdmin\Renderers\Page::make()->title('我是标题'); // 或者你可以直接写个数组 (有点丑, 而且不方便维护~ 不推荐) // [ // 'type'=>'page', // 'title'=>'我是标题', // 'body'=>'content' // ] ``` -------------------------------- ### Handle File Upload Display Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Manages file upload display issues by adjusting file paths. It removes the domain when setting the file path (e.g., for storage) and adds it back when retrieving the path (e.g., for display). A separate function is provided for handling multiple files. ```APIDOC file_upload_handle():\Illuminate\Database\Eloquent\Casts\Attribute // 多文件 file_upload_handle_multi():\Illuminate\Database\Eloquent\Casts\Attribute ``` -------------------------------- ### Call Amis Component Class Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Invokes the Component class to create a versatile Amis component. This snippet demonstrates three equivalent ways to achieve the same result: using the global `amis()` helper, directly calling `Page::make()`, and chaining methods from the `amis()` helper. ```php amis('page')->title('title')->body('content'); // 等效于 Page::make()->title('title')->body('content'); // 等效于 amis()->Page()->title('title')->body('content'); ``` -------------------------------- ### Handle Resource Detail Requests in PHP Controller Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `show` method in the controller manages requests for displaying resource details. If the `_action=getData` parameter is present, it fetches and returns the raw detail data via the service. Otherwise, it constructs and returns an Amis detail page structure, including a card layout with a title and a back button, by calling the `detail` method. ```php /** * 详情 (AdminController 中) * * @param $id * * @return JsonResponse|JsonResource * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function show($id) { // 判断参数, 查询详情并返回 if ($this->actionOfGetData()) { return $this->response()->success($this->service->getDetail($id)); } $detail = amis() ->Card() ->className('base-form') ->header(['title' => __('admin.detail')]) ->body($this->detail()) // 这里调用了 detail 方法 // 工具栏 ->toolbar([ $this->backButton() // 返回按钮 ]); $page = $this->basePage()->body($detail); return $this->response()->success($page); } ``` -------------------------------- ### Dynamically Add Menu Items using Admin::menu() in PHP Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/dynamic-add-menu.md This PHP code demonstrates how to use the `\Slowlyo\OwlAdmin\Admin::menu()->add()` method to dynamically add both parent and child menu items to the OwlAdmin framework. It illustrates how to specify properties such as ID, title, URL, URL type, icon, parent ID, and order for each menu entry. ```php // file: app/Admin/bootstrap.php \Slowlyo\OwlAdmin\Admin::menu()->add([ [ 'id' => 998, // 此处 id 用于确定父级菜单,与菜单表中的数据 'title' => 'Parent', // 菜单标题 'url' => '/parent', // 菜单路径 'url_type' => \Slowlyo\OwlAdmin\Models\AdminMenu::TYPE_ROUTE, // 菜单类型 'order' => 0 // 排序 (越小越靠前) ], [ 'id' => 999, 'title' => 'Children', 'url' => '/children', 'url_type' => '1', 'icon' => 'mdi:code-json', // 图标 'parent_id' => 998, // 父级菜单 id 'order' => 999 ] ]); ``` -------------------------------- ### Standard Owl Admin Minor/Patch Version Upgrade Procedure Source: https://github.com/owl-admin/docs/blob/master/docs/changelog/index.md This procedure outlines the common steps to upgrade Owl Admin to the latest minor or patch version. It involves updating the Composer dependency, publishing necessary assets, and conditionally updating modules. Note that the `admin:publish` command may sometimes include the `--lang` flag (e.g., `php artisan admin:publish --assets --lang --force`) depending on the version or specific requirements. ```Shell composer update slowlyo/owl-admin php artisan admin:publish --assets --force # If modules are used, execute: php artisan admin-module:update ``` -------------------------------- ### Add Multiple Components (InputText, Button) to Page Body Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Demonstrates how to add multiple components, specifically an input text field and a button, to the page's body. Components are passed as an array to the `body()` method, allowing for sequential arrangement. ```php // ... $page->body([ Slowlyo\SlowAdmin\Renderers\Form\InputText::make()->name('username')->label('姓名'), // button ]); ``` -------------------------------- ### Throw Admin Exceptions Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Provides functions to throw exceptions and return error messages. `admin_abort` throws an exception directly, while `admin_abort_if` conditionally throws an exception only if a specified flag is true. ```APIDOC admin_abort($message = '', $data = [], $doNotDisplayToast = 0); // 如果条件成了, 则抛出异常 admin_abort_if($flag, $message = '', $data = [], $doNotDisplayToast = 0); ``` -------------------------------- ### Implement Component-Level Authorization with permission() Method Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Illustrates how to apply authorization to a component using the `permission()` method. By passing a permission slug, the component will only be rendered if the current user has the specified permission, otherwise, it will not be displayed. ```php // 当前用户不是超级管理员并且没有 user.index 权限时, 按钮将不会显示 amis()->Action()->label('我是按钮')->permission('user.index'); ``` -------------------------------- ### Handle Add Form Submission with store Method in AdminController Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/create.md This snippet describes the `store` method within the `AdminController`, which is responsible for processing submitted add forms. It outlines the submission flow from the frontend to the backend. The method handles various scenarios, including quick edits, and returns a `JsonResponse` or `JsonResource`. It also notes that this method can be overridden for specific requirements, though often overriding the service layer's `store` method is sufficient. ```php /** * 新增保存 * * @param Request $request * * @return JsonResponse|JsonResource */ public function store(Request $request) { $response = fn($result) => $this->autoResponse($result, __('admin.save')); // 处理快速编辑 if ($this->actionOfQuickEdit()) { return $response($this->service->quickEdit($request->all())); } // 处理快速编辑某项 if ($this->actionOfQuickEditItem()) { return $response($this->service->quickEditItem($request->all())); } // 返回新增结果 return $response($this->service->store($request->all())); } ``` ```php /** * service 中实际处理新增逻辑的方法, 可以在自己的 service 中重写该方法 * * @param $data * * @return bool */ public function store($data): bool { $columns = $this->getTableColumns(); $model = $this->getModel(); foreach ($data as $k => $v) { if (!in_array($k, $columns)) { continue; } $model->setAttribute($k, $v); } return $model->save(); } ``` -------------------------------- ### Owl Admin v3.0.0 Major Version Upgrade Procedure Source: https://github.com/owl-admin/docs/blob/master/docs/changelog/index.md Instructions for upgrading to Owl Admin version 3.0.0, which includes significant architectural changes. This process involves updating the core framework, running a specific migration command, and an optional step to refactor deprecated function calls. ```Shell composer require slowlyo/owl-admin:v3.0.0 php artisan admin:update --v=300 # Optional: Global search for `amisMake(` and replace with `amis(` ``` -------------------------------- ### Laravel Pipeline Adaptation Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Encapsulates the Laravel pipeline function within the framework to ensure compatibility with Laravel 9. This helper facilitates fluent processing of data through a series of defined pipes. ```php admin_pipeline($passable)->through($pipes)->then(fn($i) => $i); ``` -------------------------------- ### Add Button Component to Page Body in owl-admin Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Shows how to add a button component to the page's body. It uses `Slowlyo\SlowAdmin\Renderers\Button::make()` to create a button, sets its label and level, and then passes it to the `body()` method of the page object. ```php // ... $page->body( \Slowlyo\SlowAdmin\Renderers\Button::make()->label('我是按钮')->level('primary'); ); // ... ``` -------------------------------- ### Generate Amis List Page Structure in PHP Controller Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `list` method is responsible for constructing the Amis frontend list page structure. It configures the CRUD interface, including the header toolbar with create and other action buttons, a filter form with a keyword search, and defines table columns like 'id' and 'name'. It also sets up row actions such as edit and delete buttons, integrating with base CRUD configurations. ```php public function list() { // baseCRUD 方法中, 配置了部分基础配置, 如果需要修改, 可以直接在后面覆盖 $crud = $this->baseCRUD() // CRUD 的顶部工具栏 ->headerToolbar([ $this->createButton(true), // 新增按钮 ...$this->baseHeaderToolBar(), // 工具栏内的其他操作按钮 ]) // 筛选器 ->filter( // baseFilter 方法中配置了一个基础的表单 $this->baseFilter()->body([ // 这里边配置筛选的表单项 amis()->TextControl('keyword', __('admin.keyword')) ]) ) // 判断是否可以批量操作 ->itemCheckableOn('${items[index].state > 0}') // 表格列 ->columns([ amis()->TableColumn('id', 'ID')->sortable(), amis()->TableColumn('name', __('admin.admin_user.name')), // 行操作按钮 $this->rowActions([ $this->rowEditButton(true), // 编辑按钮 $this->rowDeleteButton(), // 删除按钮 ]), ]); // baseList 方法中是基础的页面配置 return $this->baseList($crud); } ``` -------------------------------- ### Using `admin_pages` Method in PHP Source: https://github.com/owl-admin/docs/blob/master/docs/guide/built-in/pages.md This PHP snippet demonstrates how to utilize the `admin_pages` method to fetch a page schema based on a given identifier. The retrieved schema is then returned as a successful API response, enabling the dynamic rendering of content. ```php public function index(){ // admin_pages 方法,传入页面标识, 返回页面结构 $schema = admin_pages('page_sign'); return $this->response()->success($schema); } ``` -------------------------------- ### Build Add Form with form Method Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/create.md This section details how the `form` method is used to construct forms for adding new data. It explains its role in both page mode (accessed via `create` route) and modal mode (accessed via `createButton` method). The method returns a `Form` object, which frontend AMIS uses to render the form. It also mentions the `isEdit` parameter for conditional logic and the `baseForm` method for common form configurations. ```php /** * 前端 amis 通过识别 form 方法返回的结构来构建表单 * * @param bool $isEdit 用于判断是否为编辑 * * @return Form */ public function form($isEdit) { // baseForm 方法中, 处理了表单的一些基础内容 // 可以传入一个 bool 参数, 控制在表单提交成功后是否返回上一页 return $this->baseForm()->body([ TextControl::make()->name('name')->label('Name'), TextControl::make()->name('email')->label('Email'), ]); } ``` -------------------------------- ### Set Page Title using Slowlyo\SlowAdmin\Renderers\Page Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/component-use.md Illustrates how to assign a title to an existing page object. The `title()` method is called on the page instance, taking the desired title string as an argument. ```php // ... $page->title('我是标题'); // ... ``` -------------------------------- ### Encrypt String with admin_encode Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Encrypts a given string using the `admin_encode` function. This function is typically used for securing sensitive data within the application. ```APIDOC admin_encode(string $str):string ``` -------------------------------- ### Handle Edit Form Submission with `update` Method Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/update.md This section illustrates how the `update` method processes submitted edit forms. It includes both the controller's `update` method, which delegates to the service, and the service's `update` method, which contains the actual logic for saving changes to the model. It highlights that the controller's `update` method can often be used as-is, but the service's `update` method is the primary point for custom modification. ```php /** * 编辑保存 * * @param Request $request * * @return JsonResponse|JsonResource */ public function update(Request $request) { $result = $this->service->update($this->getPrimaryValue($request), $request->all()); return $this->autoResponse($result, __('admin.save')); } /** * service 中实际处理修改逻辑的方法, 可以在自己的 service 中重写该方法 * * @param $primaryKey * @param $data * * @return bool */ public function update($primaryKey, $data): bool { $columns = $this->getTableColumns(); $model = $this->query()->whereKey($primaryKey)->first(); foreach ($data as $k => $v) { if (!in_array($k, $columns)) { continue; } $model->setAttribute($k, $v); } return $model->save(); } ``` -------------------------------- ### Implementing Full Custom Export Logic (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/export.md This PHP code snippet demonstrates how to completely customize the data export logic by overriding the `export()` method in the controller. This method is invoked when the `_action=export` request parameter is present. It handles file path generation, filters data based on selected IDs or the full list query, uses `fastexcel` for the export process, and includes basic error handling. ```php // 在控制器中重写 export 方法 // 此方法在 index() 中被调用, 当请求参数 _action=export 时 protected function export() { // 默认在 storage/app/ 下 $path = sprintf('%s-%s.xlsx', $this->exportFileName(), date('YmdHis')); // 导出本页和导出选中项都是通过 _ids 查询 $ids = request()->input('_ids'); // listQuery() 为列表查询条件,与获取列表数据一致 $query = $this->service->listQuery() ->when($ids, fn($query) => $query->whereIn($this->service->primaryKey(), explode(',', $ids))); try { fastexcel($query->get())->export(storage_path('app/' . $path), fn($row) => $this->exportMap($row)); } catch (\Throwable $e) { admin_abort(__('admin.action_failed')); } return $this->response()->success(compact('path')); } ``` -------------------------------- ### Generate Amis Detail Page Structure in PHP Controller Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `detail` method in the controller is responsible for returning the Amis structure for a detail page. It utilizes `baseDetail()` to establish the foundational page layout and then adds specific static controls, such as an 'ID' field, to display resource information. This generated structure is interpreted by the frontend to render the detail view. ```php /** * 前端 amis 通过识别 detail 方法返回的结构来详情页面 * * @param bool $id 对应的主键 * * @return Form */ public function detail($id) { return $this->baseDetail()->body([ amis()->StaticExactControl()->name('id')->label('ID'), ]); } ``` -------------------------------- ### Change Application Locale to Chinese Source: https://github.com/owl-admin/docs/blob/master/docs/faq/set-zh-cn.md This code snippet demonstrates how to modify the `locale` setting in the `config/app.php` file to switch the application's language from English to Simplified Chinese (`zh_CN`). The diff format highlights the specific line change required. ```diff - 'locale' => 'en' ← 原本长这样 + 'locale' => 'zh_CN' ← 改成这样 ``` -------------------------------- ### Build Data List Query in PHP Service Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `listQuery` method in the service layer constructs the Eloquent query builder for list data retrieval. It initializes the query from the model, then applies sorting and searchable attributes based on the CRUD configuration. This method is designed to be easily overridden, allowing developers to customize the base query logic for specific list requirements. ```php /** * 列表 获取查询 (大多数情况下, 只需要重写这个方法即可) * * @return Builder */ public function listQuery() { $query = $this->query(); // 对应模型的 query 方法 $this->sortable($query); // 处理排序 $this->searchable($query); // 处理 CRUD 的 searchable 属性 return $query; // 返回查询条件 } ``` -------------------------------- ### Watermark Component Properties Reference Source: https://github.com/owl-admin/docs/blob/master/docs/guide/extension-component/watermark.md Documents the configurable properties of the Ant Design Watermark component, including layout, appearance, and content settings. These properties allow customization of the watermark's position, size, rotation, text, and image. ```APIDOC Watermark Properties: className: string - DOM class name for the watermark element. width: number - Width of the watermark; content defaults to its own width. height: number - Height of the watermark; content defaults to its own height. rotate: number - Rotation angle in degrees when drawing the watermark. zIndex: number - z-index of the appended watermark element. image: string - Image source (e.g., URL or base64); recommended to export 2x or 3x images; high priority. content: string | string[] - Text content of the watermark. font: object - Text style configuration. Refer to Ant Design documentation for specific properties (e.g., color, fontSize). gap: [number, number] - Spacing between watermarks in [horizontal, vertical] pixels. offset: [number, number] - Offset from the top-left corner of the container, defaults to gap/2. ``` -------------------------------- ### Composer: Switch to Official Packagist Source Source: https://github.com/owl-admin/docs/blob/master/docs/faq/composer-repos.md This snippet provides shell commands to revert Composer's repository configuration for Packagist. It first unsets the project-specific configuration and then the global configuration, ensuring Composer uses the official, up-to-date Packagist source. ```shell # 取消当前项目配置 composer config --unset repos.packagist # 取消全局配置 composer config -g --unset repos.packagist ``` -------------------------------- ### Data Echo/Display for Edit Forms Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/update.md This snippet demonstrates how data is retrieved and displayed (echoed) in edit forms. It shows the controller's `edit` method, which checks for a `_action=getData` parameter to trigger data retrieval via the service. The service's `getEditData` method is responsible for fetching the specific model data based on the provided ID, making sure to hide timestamp columns. ```php /** * 获取编辑页面 * * @param $id * * @return JsonResponse|JsonResource */ public function edit($id) { $this->isEdit = true; if ($this->actionOfGetData()) { return $this->response()->success($this->service->getEditData($id)); } // ... } /** * 编辑 获取数据 (Service 中) * * @param $id * * @return Model|\Illuminate\Database\Eloquent\Collection|Builder|array|null */ public function getEditData($id) { $model = $this->getModel(); return $this->query()->find($id)->makeHidden([$model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); } ``` -------------------------------- ### Convert Array to Tree Structure Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Recursively generates a tree-like data structure from a flat array. This function requires that each element in the input array contains a `parent_id` key to establish hierarchical relationships. ```APIDOC array2tree($arr):array ``` -------------------------------- ### Retrieve Single Resource Detail in PHP Service Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `getDetail` method in the service layer retrieves a single resource by its primary key (`$id`). It leverages the model's query builder to find the specific record, providing the necessary data for the detail view. This method is fundamental for populating the detail page with accurate and complete resource information. ```php /** * 详情 获取数据 (Service 中) * * @param $id * * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|Model|null */ public function getDetail($id) { return $this->query()->find($id); } ``` -------------------------------- ### Decrypt String with admin_decode Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Decrypts a given string using the `admin_decode` function. This function is the counterpart to `admin_encode`, used to retrieve original data. ```APIDOC admin_decode(string $str):string ``` -------------------------------- ### Illustrate Data Structure Transformation After Eager Loading Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/model-relation.md Compares the data structure of a model before and after applying eager loading. It shows how a flat array transforms into a nested structure, where the `branch` relationship's data is embedded directly within the parent model's array, making related data readily accessible. ```json // 直观一点看 // 原本数据长这样 [ 'id' => 1, 'name' => '张三', 'branch_id' => 1, ] // 现在数据长这样 [ 'id' => 1, 'name' => '张三', 'branch_id' => 1, 'branch' => [ 'id' => 1, 'name' => '总部', ], ] ``` -------------------------------- ### Adding Export Button to List Toolbar (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/export.md This PHP code snippet demonstrates how to add an export button to the list toolbar within the `list()` method of a controller. It utilizes the `exportAction()` method provided by the framework to enable data export functionality, typically alongside other header toolbar elements. ```php // 在列表工具栏添加导出按钮 public function list(): Page { $crud = $this->baseCRUD() ->headerToolbar([ $this->createButton(), ...$this->baseHeaderToolBar(), // 添加导出按钮 $this->exportAction(), ]) ->columns([ // ... ]); return $this->baseList($crud); } ``` -------------------------------- ### Implementing Deletion Logic in AdminController and Service (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/delete.md This PHP code snippet illustrates the backend deletion logic. The `destroy()` method in the `AdminController` handles incoming delete requests, passing the IDs to the service layer. The `delete()` method within the service is responsible for executing the actual database deletion. Developers can override the service's `delete()` method to implement custom deletion logic. ```php /** * 删除 * * @param $ids * * @return JsonResponse|JsonResource */ public function destroy($ids) { $rows = $this->service->delete($ids); return $this->autoResponse($rows, __('admin.delete')); } /** * service 中实际处理删除逻辑的方法, 可以在自己的 service 中重写该方法 * * @param string $ids * * @return mixed */ public function delete(string $ids): mixed { return $this->query()->whereIn($this->primaryKey(), explode(',', $ids))->delete(); } ``` -------------------------------- ### Customizing Export Column Mapping (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/export.md This PHP code snippet illustrates how to customize the mapping of data columns for export by overriding the `exportMap()` method in the controller. It takes a row array as input and returns an associative array where keys are desired column headers and values are the corresponding row data. It's crucial to avoid I/O operations within this method as it is called in a loop for each row. ```php // 在控制器中重写 exportMap 方法, $row 是数组格式 // 该方法会被循环调用, 请不要在里面执行 IO 操作 protected function exportMap($row) { return [ '姓名' => $row['name'], '年龄' => $row['age'], '性别' => $row['gender'], '...' ]; } ``` -------------------------------- ### Retrieve Paginated Data List in PHP Service Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/read.md This PHP `list` method in the service layer handles the actual data retrieval for lists. It first processes query conditions by calling `listQuery()`, then performs a paginated query using `paginate()`. Finally, it returns an associative array containing the retrieved `items` and the `total` count, ready for consumption by the controller or API. ```php /** * 列表 获取数据 * * @return array */ public function list() { // 处理查询条件 $query = $this->listQuery(); // 分页查询数据 $list = $query->paginate(request()->input('perPage', 20)); $items = $list->items(); $total = $list->total(); return compact('items', 'total'); } ``` -------------------------------- ### Configuring Delete Buttons in CRUD List (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/delete.md This PHP code snippet demonstrates how to configure bulk and row-level delete buttons within an `amis` CRUD list. The `list()` method in the controller sets up the CRUD component, including `bulkActions` for batch deletion and `rowActions` for individual row deletion. Both button types are designed to send AJAX requests with selected primary keys to initiate the deletion process. ```php public function list() { $crud = $this->baseCRUD() // 配置 CRUD 组件的批量操作 ->bulkActions([ $this->bulkDeleteButton() // 批量删除按钮 // 批量删除按钮会携带选中的主键字段, 发起 ajax 请求, 实现删除功能 ]) ->columns([ amis()->TableColumn()->label('ID')->name('id')->sortable(), // ... // 这里是列表的行内操作按钮 $this->rowActions([ $this->rowEditButton(true), // 编辑按钮 $this->rowDeleteButton(), // 删除按钮 // 删除按钮会携带主键字段, 发起 ajax 请求, 实现删除功能 ]), ]); return $this->baseList($crud); } ``` -------------------------------- ### Eager Load Related Data in Laravel Service Queries Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/model-relation.md Demonstrates modifying Laravel service queries to eager load related models using the `with()` method. This approach optimizes data retrieval by fetching associated `branch` data along with the primary model, preventing N+1 query issues in both list and detail views. ```php // 列表中 public function listQuery() { $model = $this->getModel(); // 原本的查询长这样 // return $this->query()->orderByDesc($model->getUpdatedAtColumn()); // 现在你需要改成这样, 预加载 branch 关联 return $this->query()->with('branch')->orderByDesc($model->getUpdatedAtColumn()); } // 详情中 public function getDetail($id) { // 原本的查询长这样 // return $this->query()->find($id); // 现在你需要改成这样, 预加载 branch 关联 return $this->query()->with('branch')->find($id); } ``` -------------------------------- ### Check if String is JSON Source: https://github.com/owl-admin/docs/blob/master/docs/guide/basic/helper.md Determines whether a given string is a valid JSON string. This is useful for validating input or parsing data. ```APIDOC is_json(string $str):bool ``` -------------------------------- ### Customizing Export File Name (PHP) Source: https://github.com/owl-admin/docs/blob/master/docs/guide/crud/export.md This PHP code snippet shows how to override the default export file name by implementing the `exportFileName()` method in the controller. This allows for dynamic or custom naming of the exported .xlsx file, providing more control over the output file's identity. ```php // 在控制器中重写 exportFileName 方法 protected function exportFileName() { return '此处为导出文件名'; } ``` -------------------------------- ### Display Nested Related Data in Amis UI Components Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/model-relation.md Shows how to access and display nested related data (e.g., `branch.name`) within Amis UI components like `TableColumn` and `TextControl`. This leverages Amis's data binding capabilities, allowing direct referencing of properties from eager-loaded relationships for frontend display. ```php // 列表中 // ... // 你现在可以通过 . 的方式取到多个层级的数据 TableColumn::make()->name('branch.name')->label('所属分公司'), // ... // 详情中 // ... // 你现在可以通过 . 的方式取到多个层级的数据 TextControl::make()->static(true)->name('branch.name')->label('所属分公司'), // ... ``` -------------------------------- ### Define Laravel Eloquent `belongsTo` Relationship Source: https://github.com/owl-admin/docs/blob/master/docs/guide/examples/model-relation.md Illustrates how to define a `belongsTo` relationship in a Laravel Eloquent model. This method establishes an inverse one-to-one or one-to-many connection, indicating that the current model belongs to another model, such as a `Branch`. ```php public function branch() { return $this->belongsTo(Branch::class); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.