In order for the created template to be used instead of the standard one, you must specify it in the configuration file, just as if passing an argument in the `view('brand.header')` helper:
'template' => [\
'header' => 'brand.header',\
'footer' => null,\
],
> **Note.** The configuration file may be cached, and the changes will not take effect until the `php artisan config:clear` command is executed
In the same way, we can change the bottom of the page, again create a new file `/resources/views/brand/footer.blade.php` with the following contents:
Also making changes to the configuration file:
'template' => [\
'header' => 'brand.header',\
'footer' => 'brand.footer',\
],
> **Note**. If you want the text or images to be different for the login and panel pages, you can use [Authentication Directives](https://laravel.com/docs/blade#authentication-directives)
> .
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Form Builder | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/builder/# "Scroll to the top of the page")
Form Builder
============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/builder.md "View and edit this file on GitHub")
* [Introduction](https://orchid.software/en/docs/builder/#introduction)
* [Data Binding](https://orchid.software/en/docs/builder/#data-binding)
* [Creating a Field](https://orchid.software/en/docs/builder/#creating-a-field)
[Introduction](https://orchid.software/en/docs/builder/#introduction)
----------------------------------------------------------------------
Describing form fields can be a challenging task, but with `Orchid\Screen\Builder`, you can easily modify and reuse form fields using a single builder that generates `HTML` code.
To build a form, you need to provide the field definitions and possibly a data source:
use Orchid\Screen\Builder;
use Orchid\Screen\Fields\Input;
// Initialize the form builder with the field definitions
$builder = new Builder([\
Input::make('name'),\
]);
// Generate HTML code for the form
$html = $builder->generateForm();
[Data Binding](https://orchid.software/en/docs/builder/#data-binding)
----------------------------------------------------------------------
To specify the value of an element, you must specify the data source. By providing the specified key, the data will automatically replace the corresponding field.
For example:
use Orchid\Screen\Builder;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Repository;
$fields = [\
Input::make('name'),\
];
$repository = new Repository([\
'name' => 'Alexandr Chernyaev',\
]);
$builder = new Builder($fields, $repository);
$html = $builder->generateForm();
It is also possible to access nested objects using `dot`\-notation.
$fields = [\
Input::make('name.ru'),\
];
$repository = new Repository([\
'name' => [\
'en' => 'Alexandr Chernyaev',\
'ru' => 'Александр Черняев',\
],\
]);
$builder = new Builder($fields, $repository);
$html = $builder->generateForm();
You can also set the desired language and prefix using the `setLanguage` method:
$fields = [\
Input::make('name'),\
];
$repository = new Repository([\
'en' => [\
'name' => 'Alexandr Chernyaev',\
],\
'ru' => [\
'name' => 'Александр Черняев',\
]\
]);
$builder = new Builder($fields, $repository);
$builder->setLanguage('en');
$html = $builder->generateForm();
[Creating a Field](https://orchid.software/en/docs/builder/#creating-a-field)
------------------------------------------------------------------------------
Every field is just a setting above the view that passes data to the template. Here is an example of how to create custom input fields by using the `Field` class.
namespace App\Orchid\Fields;
use Orchid\Screen\Field;
class CustomField extends Field
{
/**
* Blade template
*
* @var string
*/
protected $view = '';
/**
* Default attributes value.
*
* @var array
*/
protected $attributes = [];
/**
* Attributes available for a particular tag.
*
* @var array
*/
protected $inlineAttributes = [];
}
The `view` property is determined by the blade. `attributes` lists default values, and `inlineAttributes` define keys in html format, for example:
First name:
In this example, the inline attribute is type and name specified directly in the tag. And the `make()` method is only for quick and convenient initialization, since any form that should add or modify data must possess it.
We only update that the created class and add the blade template, using the example above:
{{ $title }}:
In order to try a new field, you must use the built-in `render()` method:
$input = CustomField::make('name');
$html = $input->render(); // html string
The `html` variable will contain the template just specified, try adding some elements:
$input = CustomField::make('name')
->title('How your name?')
->placeholder('Sheldon Cooper')
->value('Alexandr Chernyaev');
$html = $input->render();
After we refresh the page, a new title is displayed on it, instead of the default, but neither placeholder nor value was applied. It is because they were not specified in the `inlineAttributes`, fix this:
/**
* Attributes available for a particular tag.
*
* @var array
*/
protected $inlineAttributes = [\
'name',\
'type',\
'placeholder',\
'value'\
];
After that, each attribute will be drawn in our template.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Cell Types | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/cell-types/# "Scroll to the top of the page")
Cell Types
==========
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/cell-types.md "View and edit this file on GitHub")
* [Introduction](https://orchid.software/en/docs/cell-types/#introduction)
* [DateTimeSplit](https://orchid.software/en/docs/cell-types/#datetimesplit)
* [Number](https://orchid.software/en/docs/cell-types/#number)
* [Boolean](https://orchid.software/en/docs/cell-types/#boolean)
* [Percentage](https://orchid.software/en/docs/cell-types/#percentage)
* [Currency](https://orchid.software/en/docs/cell-types/#currency)
[Introduction](https://orchid.software/en/docs/cell-types/#introduction)
-------------------------------------------------------------------------
When working on your project, you’ll often encounter the need to present various data types such as currency, numbers, or dates. Orchid makes this task easier by providing built-in components that handle these common data types, similar to popular spreadsheet software like Microsoft Excel or Apple Numbers.
Orchid’s components help you avoid code duplication and allow you to effortlessly format and display your data. **These components can be used for both [table cells](https://orchid.software/en/docs/table)
(using the `TD` class) and [legends](https://orchid.software/en/docs/legend)
(using the `Sight` class)**. In this documentation, we will primarily cover the usage of `TD` components.
[DateTimeSplit](https://orchid.software/en/docs/cell-types/#datetimesplit)
---------------------------------------------------------------------------
The `DateTimeSplit` component is specifically designed to display dates in a two-line format. The top line shows the formatted date, while the bottom line provides additional details such as the day of the week and the time.
To use the `DateTimeSplit` component, you can specify the attribute that contains the date information and include it in your table cell definition:
TD::make('created_at')
->usingComponent(DateTimeSplit::class),
By default, Orchid provides sensible formatting options for the upper and lower parts of the cell. However, you can also customize these options to match your specific requirements. For example, you can change the format of the date or adjust the timezone:
use Orchid\Screen\Components\Cells\DateTimeSplit;
TD::make('created_at')
->usingComponent(DateTimeSplit::class, upperFormat: 'Y-m-d', lowerFormat: 'H:i:s.uP', timeZone: 'Europe/Madrid'),
In the above example, we set the `upperFormat` option to `'Y-m-d'` to display the date in the format 'YYYY-MM-DD’. The `lowerFormat` option is set to `'H:i:s.uP'`, which shows the time in the format 'HH:MM:SS.microseconds+timezone’. Feel free to adjust these formats and the `timeZone` option to suit your project’s needs.
> **Note:** This documentation assumes familiarity with the PHP [Named Arguments](https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments)
> feature.
[Number](https://orchid.software/en/docs/cell-types/#number)
-------------------------------------------------------------
The `Number` component simplifies the formatting and display of numerical data. It allows you to present numbers in a desired format, such as with thousands separators for improved readability.
To use the `Number` component, specify the attribute containing the numerical value within your table cell definition:
use Orchid\Screen\Components\Cells\Number;
TD::make('value')
->usingComponent(Number::class),
When the component encounters a large number, it automatically adds thousands separators to enhance readability. For example, the value `100400500.75` will be rendered as `100 400 500,8`.
In addition to the default behavior, you can customize the `Number` component by specifying options such as the number of decimal places, decimal separators, and thousands separators:
TD::make('value')
->usingComponent(Number::class, decimals: 1, decimal_separator: ',', thousands_separator: ' '),
[Boolean](https://orchid.software/en/docs/cell-types/#boolean)
---------------------------------------------------------------
The `Boolean` component is designed to represent boolean values in a concise and visually clear manner. It allows you to display boolean data with appropriate labels.
Here’s an example of using the `Boolean` component:
use Orchid\Screen\Components\Cells\Boolean;
TD::make('value')
->usingComponent(Boolean::class),
By default, the `Boolean` component will display boolean values as “true” or “false”. However, you can easily customize the labels to match the semantics of your data:
TD::make('value')
->usingComponent(Boolean::class, true: 'Enabled', false: 'Disabled'),
[Percentage](https://orchid.software/en/docs/cell-types/#percentage)
---------------------------------------------------------------------
The `Percentage` component simplifies the presentation of values as percentages. It automatically formats the values and adds the percentage symbol for clear visual representation.
To use the `Percentage` component, specify the attribute that contains the numerical value within your table cell definition:
use Orchid\Screen\Components\Cells\Percentage;
TD::make('value')
->usingComponent(Percentage::class),
The `Percentage` component provides a clear and concise representation of the numeric value as a percentage. You can also customize the component by specifying the number of decimal places to display:
TD::make('value')
->usingComponent(Percentage::class, decimals: 2),
[Currency](https://orchid.software/en/docs/cell-types/#currency)
-----------------------------------------------------------------
The `Currency` component simplifies the formatting and display of currency values. It ensures consistent formatting and provides options for customization.
To use the `Currency` component, specify the field and use the `usingComponent` method:
use Orchid\Screen\Components\Cells\Currency;
TD::make('value')
->usingComponent(Currency::class),
The `Currency` component automatically formats the currency value using the appropriate currency symbol and decimal separators. However, you can also customize the formatting by specifying additional options. For example:
TD::make('value')
->usingComponent(Currency::class, decimals: 1, decimal_separator: ',', thousands_separator: ' '),
If you need to use custom currency symbols, you can specify them using the `before` and `after` options. For example:
TD::make('value')
->usingComponent(Currency::class, before: '$', after: '₽'),
In this case, the currency value is displayed with a dollar sign before the value and a ruble symbol after the value. Adjust these options to match the currency symbols used in your project.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Charts | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/charts/# "Scroll to the top of the page")
Charts
======
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/charts.md "View and edit this file on GitHub")
* [Basic Configuration](https://orchid.software/en/docs/charts/#basic-configuration)
* [Adjusting Height](https://orchid.software/en/docs/charts/#adjusting-height)
* [Customizing Colors](https://orchid.software/en/docs/charts/#customizing-colors)
* [Exporting Images](https://orchid.software/en/docs/charts/#exporting-images)
* [Adding Markers](https://orchid.software/en/docs/charts/#adding-markers)
* [Eloquent Model](https://orchid.software/en/docs/charts/#eloquent-model)
* [Grouped Data](https://orchid.software/en/docs/charts/#grouped-data)
* [Working with Time Periods](https://orchid.software/en/docs/charts/#working-with-time-periods)
* [Value Query Types](https://orchid.software/en/docs/charts/#value-query-types)
Chart layout may be generated using the `orchid:chart` Artisan command. By default, all new metrics will be placed in the `app/Orchid/Layouts` directory:
php artisan orchid:chart ChartsLayout
Once your chart class has been generated, you’re ready to customize it. Example:
namespace App\Orchid\Layouts;
use Orchid\Screen\Layouts\Chart;
class ChartsLayout extends Chart
{
/**
* Available options:
* 'bar', 'line',
* 'pie', 'percentage'
*
* @var string
*/
protected $type = 'bar';
}
By creating and setting up a visual representation of the class, we can use it in the future. But before using chart, we need to prepare the data we want to display. To do this, let’s set the `query` value of the screen:
public function query() : array
{
$dataset = [\
[\
'labels' => ['12am-3am', '3am-6am', '6am-9am', '9am-12pm', '12pm-3pm', '3pm-6pm', '6pm-9pm'],\
'name' => 'Some Data',\
'values' => [25, 40, 30, 35, 8, 52, 17, -4],\
],\
[\
'labels' => ['12am-3am', '3am-6am', '6am-9am', '9am-12pm', '12pm-3pm', '3pm-6pm', '6pm-9pm'],\
'name' => 'Another Set',\
'values' => [25, 50, -10, 15, 18, 32, 27, 14],\
],\
[\
'labels' => ['12am-3am', '3am-6am', '6am-9am', '9am-12pm', '12pm-3pm', '3pm-6pm', '6pm-9pm'],\
'name' => 'Yet Another',\
'values' => [15, 20, -3, -15, 58, 12, -17, 37],\
],\
];
return [\
'dataset' => $dataset,\
];
}
Now we can use the layout class by calling the static method `make` and specifying the target key for the data:
use App\Orchid\Layouts\ChartsLayout;
public function layout(): iterable
{
return [\
ChartsLayout::make('dataset', 'Header for our dataset'),\
];
}
Often datasets need a little explanation, we can add a description for that:
use App\Orchid\Layouts\ChartsLayout;
public function layout(): iterable
{
return [\
ChartsLayout::make('dataset', 'Header for our dataset'),\
->description('Description of the chart')\
];
}
[Basic Configuration](https://orchid.software/en/docs/charts/#basic-configuration)
-----------------------------------------------------------------------------------
The configuration is used to change how the chart behaves. There are properties to control styling, height, etc.
### [Adjusting Height](https://orchid.software/en/docs/charts/#adjusting-height)
Set the height of the chart in pixels by specifying the property:
/**
* @var int
*/
protected $height = 250;
### [Customizing Colors](https://orchid.software/en/docs/charts/#customizing-colors)
Set the colors that will be used for each individual unit type, depending on the type of chart by specifying a property:
/**
* Colors used.
*
* @var array
*/
protected $colors = [\
'#2274A5',\
'#F75C03',\
'#F1C40F',\
'#D90368',\
'#00CC66',\
];
### [Exporting Images](https://orchid.software/en/docs/charts/#exporting-images)
Charts can be exported in the `SVG` format, in which they are displayed initially. To do this, specify the property:
/**
* Determines whether to display the export button.
*
* @var bool
*/
protected $export = true;
### [Adding Markers](https://orchid.software/en/docs/charts/#adding-markers)
Some graphs are difficult to interpret without more information. For example, show the average value. For this you can define the `markers` method:
/**
* To highlight certain values on the Y axis, markers can be set.
* They will show as dashed lines on the graph.
*/
protected function markers(): ?array
{
return [\
[\
'label' => 'Medium',\
'value' => 40,\
],\
];
}
[Eloquent Model](https://orchid.software/en/docs/charts/#eloquent-model)
-------------------------------------------------------------------------
In order to use the methods of obtaining data for charts from the model, you need to add the trait `Chartable`:
namespace App;
use Orchid\Metrics\Chartable;
use Orchid\Platform\Models\User as Authenticatable;
class User extends Authenticatable
{
use Chartable;
// ...
}
This will add several new methods specifically for charting:
* Grouped data
* A period of time
[Grouped Data](https://orchid.software/en/docs/charts/#grouped-data)
---------------------------------------------------------------------
For example, you might want to build a chart showing the proportion of users who have enabled two-factor authentication.
namespace App\Orchid\Layouts;
use Orchid\Screen\Layouts\Chart;
class BasicPieChart extends Chart
{
/**
* Available options:
* 'bar', 'line',
* 'pie', 'percentage'.
*
* @var string
*/
protected $type = 'pie';
}
Then the model query will serve as a data source `countForGroup()`
public function query(): array
{
$userUsageTwoFactorAuth = User::countForGroup('uses_two_factor_auth')->toChart();
return [\
'userUsageTwoFactorAuth' => $userUsageTwoFactorAuth,\
];
}
public function layout(): array
{
return [\
BasicPieChart::make('userUsageTwoFactorAuth', 'Usage two-factor authentication'),\
];
}
In order to change the text of headers, you can pass the closure function as the first argument:
User::countForGroup('uses_two_factor_auth')
->toChart(fn(bool $value) => $value ? 'Enabled' : 'Disabled'),
[Working with Time Periods](https://orchid.software/en/docs/charts/#working-with-time-periods)
-----------------------------------------------------------------------------------------------
Receives data for a certain period of time, filling in the missing values.
For example, let’s display a graph of new users and roles:
namespace App\Orchid\Layouts;
use Orchid\Screen\Layouts\Chart;
class BasicLineChart extends Chart
{
/**
* Available options:
* 'bar', 'line',
* 'pie', 'percentage'.
*
* @var string
*/
protected $type = 'line';
}
Then the data source will be:
public function query(): array
{
return [\
'members' => [\
User::countByDays()->toChart('Users'),\
Role::countByDays()->toChart('Roles'),\
]\
];
}
public function layout(): array
{
return [\
BasicLineChart::make('members', 'New members'),\
];
}
By default, the data will be taken for one month; to set your own period, you need to pass the arguments:
$start = Carbon::now()->subDay(7);
$end = Carbon::now()->subDay(1);
User::countByDays($start, $end)->toChart('Users')
By default, data is grouped by the `created_at` column, to change it:
$start = Carbon::now()->subDay(7);
$end = Carbon::now()->subDay(1);
User::countByDays($start, $end, 'updated_at')->toChart('Users')
### [Value Query Types](https://orchid.software/en/docs/charts/#value-query-types)
Value metrics don’t just ship with a `countByDays` method. You may also use a variety of other aggregate functions when building your metric.
The `average` method may be used to calculate the average of a given column
Order::averageByDays('price')->toChart('Order'),
The `sum` method may be used to calculate the sum of a given column:
Order::sumByDays('price')->toChart('Order'),
The `min` method may be used to calculate the min of a given column:
Order::minByDays('price')->toChart('Order'),
The `max` method may be used to calculate the max of a given column:
Order::maxByDays('price')->toChart('Order'),
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Configuration | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/configuration/# "Scroll to the top of the page")
Configuration
=============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/configuration.md "View and edit this file on GitHub")
* [Domain](https://orchid.software/en/docs/configuration/#domain)
* [Prefix](https://orchid.software/en/docs/configuration/#prefix)
* [Middleware](https://orchid.software/en/docs/configuration/#middleware)
* [Login Page](https://orchid.software/en/docs/configuration/#login-page)
* [Home Page](https://orchid.software/en/docs/configuration/#home-page)
* [Asset Resources](https://orchid.software/en/docs/configuration/#asset-resources)
* [Appearance Patterns](https://orchid.software/en/docs/configuration/#appearance-patterns)
* [Model Classes](https://orchid.software/en/docs/configuration/#model-classes)
* [Overriding Blade Templates](https://orchid.software/en/docs/configuration/#overriding-blade-templates)
The package uses the standard configuration system for Laravel. It stores the main parameters in the `config` directory, and the main file for the platform is the file `platform.php`. Each setting comes with a comment explaining its purpose.
> **Note.** After caching your configuration files, don’t forget to clear the cache if you make changes. Use the `php artisan config:clear` command to refresh it.
In this section, we will delve into the configuration file and provide a detailed description of each parameter.
[Domain](https://orchid.software/en/docs/configuration/#domain)
----------------------------------------------------------------
'domain' => env('PLATFORM_DOMAIN', null),
For many projects, the address of the location of the administration panel plays an important role. For example, the application is located at `example.com`, and the platform is at `admin.example.com` or on a third-party domain.
To specify the address you would like to use for the platform, you can set the `domain` parameter in the configuration file:
'domain' => 'admin.example.com',
It is important to note that your web server settings must be configured correctly for this to work. For example, if you are using Apache, you will need to set up a virtual host for the domain you specified in the configuration file.
[Prefix](https://orchid.software/en/docs/configuration/#prefix)
----------------------------------------------------------------
'prefix' => env('PLATFORM_PREFIX', 'admin'),
The `prefix` parameter allows you to change the default `admin` prefix to any other name, such as `orchid` or `administrator`. This is useful if you want to use a different prefix for your admin panel or if the default prefix is already in use by another part of your application.
For example, if you set the prefix to `dashboard`, the URL for the admin login page would be `https://example.com/dashboard/login` instead of `https://example.com/admin/login`.
To change the prefix, you can update the prefix parameter in the configuration file:
'prefix' => 'dashboard',
It’s worth noting that changing the prefix will also change the URL of all routes within the admin panel, so make sure to update any links or redirects that reference the old prefix.
[Middleware](https://orchid.software/en/docs/configuration/#middleware)
------------------------------------------------------------------------
'middleware' => [\
'public' => [\
'web', \
'cache.headers:private;must_revalidate;etag'\
],\
'private' => [\
'web',\
'platform',\
'cache.headers:private;must_revalidate;etag'\
],\
],
The `middleware` parameter allows you to add or change the middleware (intermediate layers) used for the admin panel. By default, the platform comes with two groups of middleware: `public` and `private`.
The `public` middleware is applied to routes that can be accessed by an unauthorized user, such as the login page. The `private` middleware, on the other hand, is applied to routes that can only be accessed by authorized users, such as the dashboard page.
You can add as many new middleware as you like. For example, you can add a middleware that filters requests from a specific IP address range or a middleware that checks for a valid API token.
[Login Page](https://orchid.software/en/docs/configuration/#login-page)
------------------------------------------------------------------------
'auth' => true,
The `auth` parameter controls whether the package uses its own simple login interface or not. By default, it is set to `true`, which means the platform will use its own login interface.
If you require more advanced features such as password recovery or two-factor authentication, you can set auth to false and use a package like [Jetstream](https://laravel.com/docs/authentication#authentication-quickstart)
or roll your own login interface.
To use a package like Jetstream, you will need to install it and configure it according to its documentation. If you roll your own login interface, you will need to create the necessary controllers, views, and routes for the login process.
'auth' => false,
[Home Page](https://orchid.software/en/docs/configuration/#home-page)
----------------------------------------------------------------------
The `index` parameter controls the main page of the admin panel that the user will see when they first log in or click on the logo or links in the navigation bar.
'index' => 'platform.main',
The default value for this parameter is `platform.main`, which corresponds to the main dashboard page of the platform.
You can change this to any other route you have defined in your application. For example, if you want to redirect users to a custom dashboard page, you can update the `index` parameter to point to that route:
'index' => 'custom.dashboard',
It’s worth noting that you will need to create the corresponding route and controller for the new home page.
[Asset Resources](https://orchid.software/en/docs/configuration/#asset-resources)
----------------------------------------------------------------------------------
'resource' => [\
'stylesheets' => [],\
'scripts' => [],\
],
The `resource` parameter allows you to add your own stylesheets or javascript scripts to the admin panel. You can globally add paths to the corresponding arrays in the configuration file.
For example, if you want to include a custom stylesheet on every page of the admin panel, you can add the path to the `stylesheets` array:
'resource' => [\
'stylesheets' => [\
'/path/to/custom.css'\
],\
'scripts' => [\
'/path/to/custom.js', // Local path in the public directory\
'https://cdn.example.com/app.js', // CDN path\
],\
],
It’s worth noting that the resource file must be present in the `public` directory to be able to access it.
[Appearance Patterns](https://orchid.software/en/docs/configuration/#appearance-patterns)
------------------------------------------------------------------------------------------
To change some templates, it is unnecessary to publish the entire package; you can customize a part of the user interface to specify a logo, accompanying documents, etc.
'template' => [\
'header' => null,\
'footer' => null,\
],
[Model Classes](https://orchid.software/en/docs/configuration/#model-classes)
------------------------------------------------------------------------------
The desire to change the behavior of some classes from the standard delivery is quite normal. For the platform to use your model classes instead of its own, it is necessary to register their substitution in advance using:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Orchid\Platform\Dashboard;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Dashboard::useModel(
\Orchid\Platform\Models\User::class,
\App\Models\User::class
);
}
}
[Overriding Blade Templates](https://orchid.software/en/docs/configuration/#overriding-blade-templates)
--------------------------------------------------------------------------------------------------------
Backend pages are created using [Blade](https://laravel.com/docs/blade)
. You can change these using Laravel’s template override mechanism (this is the same for all Laravel packages, not just Orchid);
> 🚨 **Alert!** Overridden templates do not receive updates or bug fixes. Think of this as turning off the autopilot.
Following Laravel’s mechanism for overriding templates from packages is to create the `/resources/views/vendor/platform/` directory in your application and create new templates with the same path as the original templates.
For example, to override `/vendor/orchid/platform/resources/views/partials/search.blade.php`, create a new template at `/resources/views/vendor/platform/partials/search.blade.php`. An illustrative example:
your-project/
├─ ...
└─ resources/
└─ views/
└─ vendor/
└─ platform/
└─ partials/
└─ search.blade.php
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Controllers | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/controllers/# "Scroll to the top of the page")
Controllers
===========
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/controllers.md "View and edit this file on GitHub")
There is usually no need to create custom controllers to do anything outside the package’s scope since you can place [your views on the screen](https://orchid.software/en/docs/custom-template/#views)
, no matter how complex they are.
But if, for example, you already have an implementation of the admin panel and you already have many of your controllers, then rewriting the working code is not at all necessary. By following the steps below, you will understand how to show them in the Orchid interface. Ultimately, this will shorten the transition time and allow you to upgrade in small increments.
To create a new controller, use the `make:controller` Artisan command:
php artisan make:controller OrchidController
This will generate a new class in the `app/Http/Controllers` directory. You can then modify the class as needed:
namespace App\Http\Controllers;
class OrchidController extends Controller
{
/**
* @return \Illuminate\View\View
*/
public function index()
{
return view('custom');
}
}
The `index` method of your controller should return a view template, which will be rendered using the Orchid package’s style. Here is an example of a view template:
@extends('platform::dashboard')
@section('title','title')
@section('description', 'description')
@section('navbar')
Navbar
@stop
@section('content')
Content
@stop
To make the controller accessible through the Orchid interface, you need to declare a route for it in the route file (e.g. `routes/platform`). This will ensure that common rules such as authorization apply to the controller.
Here is an example of how to declare a route for the `OrchidController`:
use App\Http\Controllers\OrchidController;
Route::get('custom', [OrchidController::class, 'index']);
You can now access your custom controller by visiting the custom route in your Orchid app.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# View Template | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/custom-template/# "Scroll to the top of the page")
View Template
=============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/custom-template.md "View and edit this file on GitHub")
* [Views](https://orchid.software/en/docs/custom-template/#views)
* [Blade Components](https://orchid.software/en/docs/custom-template/#blade-components)
* [Wrapper](https://orchid.software/en/docs/custom-template/#wrapper)
* [Browsing](https://orchid.software/en/docs/custom-template/#browsing)
[Views](https://orchid.software/en/docs/custom-template/#views)
----------------------------------------------------------------
Sometimes you may want to display your own `blade` template in your application. To do this, you can use the `Layout::view` method and pass it a string containing the name of your template.
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::view('greeting'),\
];
}
Any data returned by the `query` method will be passed to your template and can be accessed using Blade syntax. For example:
// ... Screen
public function query(): array
{
return [\
'name' => 'Alexandr Chernyaev',\
];
}
public function layout(): array
{
return [\
Layout::view('greeting'),\
];
}
In the `hello.blade.php` template, you can display the contents of the `name` variable like this:
{{-- ... /views/greeting.blade.php --}}
Hello, {{ $name }}.
Note that the `layout` method should return an array of views to be displayed in the final layout. If you want to include multiple custom templates, you can add them to the array like this:
public function layout(): array
{
return [\
Layout::view('dashboard'),\
Layout::view('users'),\
Layout::view('settings'),\
];
}
[Blade Components](https://orchid.software/en/docs/custom-template/#blade-components)
--------------------------------------------------------------------------------------
Blade components are a way to reuse templates in your Laravel application. To create a new blade component, you can use the `artisan` command:
php artisan make:component Hello --inline
This will create a new class called `Hello` in the `App\View\Components` namespace. The class should look something like this:
namespace App\View\Components;
use Illuminate\View\Component;
class Hello extends Component
{
/**
* @var string
*/
public $name;
/**
* Create a new component instance.
*
* @param string $name
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return <<<'blade'
Hello {{ $name }}!
blade;
}
}
To use the component in your screens, you can pass its lowercase representation to the `Layout::component` method:
/**
* Query data.
*
* @return array
*/
public function query(): array
{
return [\
'name' => 'Sheldon Cooper',\
];
}
/**
* Views.
*
* @return Layout[]
*/
public function layout(): array
{
return [\
Layout::component(Hello::class),\
];
}
The values returned by the `query` method will be passed to the component and can be accessed using blade syntax. For example, in the `Hello` component class, you can access the name variable like this:
Hello {{ $name }}!
If you want to pass additional variables to the component, you can do so by modifying the constructor and adding them as arguments. For example:
namespace App\View\Components;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\View\Component;
class Hello extends Component
{
/**
* @var string
*/
public $name;
/**
* @var Application
*/
public $application;
/**
* Create a new component instance.
*
* @param Application $application
* @param string $name
*/
public function __construct(Application $application, string $name)
{
$this->application = $application;
$this->name = $name;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return <<<'blade'
Hello {{ $name }}!
Version {{ $application->version() }}
blade;
}
}
You can learn more about blade components in the [Laravel documentation](https://laravel.com/docs/blade#components)
.
[Wrapper](https://orchid.software/en/docs/custom-template/#wrapper)
--------------------------------------------------------------------
A “Wrapper” is an intermediate link between a custom template and the standard layout layers. It allows you to specify where other layout layers should be displayed within your custom template.
To use a wrapper, you can pass an array of views to the `Layout::wrapper` method, along with the name of your custom template. The array should contain keys representing the variables that will be available in the template, and the values should be the views to be rendered.
public function layout(): array
{
return [\
Layout::wrapper('settings', [\
'foo' => [\
RowLayout::class,\
RowLayout::class,\
],\
'bar' => RowLayout::class,\
]),\
];
}
In the `settings.blade.php` template, you can access the `foo` and `bar` variables and display the views they contain like this:
@foreach($foo as $row)
{!! $row !!}
@endforeach
{!! $bar !!}
Note that the variables returned by the `query` method will also be available in the template and can be accessed using blade syntax.
public function query(): array
{
return [\
'name' => 'Alexandr Chernyaev',\
];
}
You can display the contents of the name variable in your template like this:
Hello, {{ $name }}.
[Browsing](https://orchid.software/en/docs/custom-template/#browsing)
----------------------------------------------------------------------
Sometimes it can be inconvenient to switch between multiple browser tabs when working in the admin panel. To avoid this, you can use the `Layout::browsing` method to display the contents of a different web page within an iframe in your application.
For example:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::browsing('http://127.0.0.1:8000/telescope'),\
];
}
You can also specify various attributes for the iframe element by chaining method calls onto the `Layout::browsing` method. For example:
Layout::browsing('http://127.0.0.1:8000/telescope')
->allow('...')
->loading('...')
->csp('...')
->name('...')
->referrerpolicy('...')
->sandbox('...')
->src('...')
->srcdoc('...');
Refer to the [HTML specification](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-iframe-element)
for a complete list of available attributes.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Form Elements | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/field/# "Scroll to the top of the page")
Form Elements
=============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/field.md "View and edit this file on GitHub")
* [Introduction to Input](https://orchid.software/en/docs/field/#introduction-to-input)
* [Designing Input Interfaces](https://orchid.software/en/docs/field/#designing-input-interfaces)
* [Required Fields](https://orchid.software/en/docs/field/#required-fields)
* [Hiding Input Fields](https://orchid.software/en/docs/field/#hiding-input-fields)
* [Types of Input](https://orchid.software/en/docs/field/#types-of-input)
* [Masking Input Values](https://orchid.software/en/docs/field/#masking-input-values)
* [TextArea](https://orchid.software/en/docs/field/#textarea)
* [CheckBox](https://orchid.software/en/docs/field/#checkbox)
* [Select](https://orchid.software/en/docs/field/#select)
* [Relation](https://orchid.software/en/docs/field/#relation)
* [DateTime](https://orchid.software/en/docs/field/#datetime)
* [Direct Input](https://orchid.software/en/docs/field/#direct-input)
* [Date Format](https://orchid.software/en/docs/field/#date-format)
* [Time Selection](https://orchid.software/en/docs/field/#time-selection)
* [Time Selection Only](https://orchid.software/en/docs/field/#time-selection-only)
* [Range Selection](https://orchid.software/en/docs/field/#range-selection)
* [Quick Date Selection](https://orchid.software/en/docs/field/#quick-date-selection)
* [Allow Empty Values](https://orchid.software/en/docs/field/#allow-empty-values)
* [Multiple Selection](https://orchid.software/en/docs/field/#multiple-selection)
* [DateRange](https://orchid.software/en/docs/field/#daterange)
* [TimeZone](https://orchid.software/en/docs/field/#timezone)
* [Quill WYSIWYG Editor](https://orchid.software/en/docs/field/#quill-wysiwyg-editor)
* [Toolbar Controls](https://orchid.software/en/docs/field/#toolbar-controls)
* [Extensibility](https://orchid.software/en/docs/field/#extensibility)
* [Markdown Editor](https://orchid.software/en/docs/field/#markdown-editor)
* [Matrix](https://orchid.software/en/docs/field/#matrix)
* [Customizing Column Headers](https://orchid.software/en/docs/field/#customizing-column-headers)
* [Limiting Rows](https://orchid.software/en/docs/field/#limiting-rows)
* [Custom Fields](https://orchid.software/en/docs/field/#custom-fields)
* [Code editor](https://orchid.software/en/docs/field/#code-editor)
* [Picture](https://orchid.software/en/docs/field/#picture)
* [Cropper](https://orchid.software/en/docs/field/#cropper)
* [Width and Height](https://orchid.software/en/docs/field/#width-and-height)
* [File Size Limit](https://orchid.software/en/docs/field/#file-size-limit)
* [Value](https://orchid.software/en/docs/field/#value)
* [Attach](https://orchid.software/en/docs/field/#attach)
* [File Upload Limitations](https://orchid.software/en/docs/field/#file-upload-limitations)
* [File Grouping](https://orchid.software/en/docs/field/#file-grouping)
* [File Storage](https://orchid.software/en/docs/field/#file-storage)
* [Explicit File Path Configuration](https://orchid.software/en/docs/field/#explicit-file-path-configuration)
* [File Validation and Sorting on the Server](https://orchid.software/en/docs/field/#file-validation-and-sorting-on-the-server)
* [Error Handling and Message Display](https://orchid.software/en/docs/field/#error-handling-and-message-display)
* [Group](https://orchid.software/en/docs/field/#group)
* [Column Width](https://orchid.software/en/docs/field/#column-width)
* [Column Alignment](https://orchid.software/en/docs/field/#column-alignment)
* [Button](https://orchid.software/en/docs/field/#button)
* [Action Confirmation](https://orchid.software/en/docs/field/#action-confirmation)
* [Submission URL](https://orchid.software/en/docs/field/#submission-url)
* [File Download](https://orchid.software/en/docs/field/#file-download)
* [Link](https://orchid.software/en/docs/field/#link)
* [Opening Link in a New Tab](https://orchid.software/en/docs/field/#opening-link-in-a-new-tab)
* [File Download](https://orchid.software/en/docs/field/#file-download)
* [Dropdown Menu](https://orchid.software/en/docs/field/#dropdown-menu)
* [NumberRange](https://orchid.software/en/docs/field/#numberrange)
* [Custom Fields Creation](https://orchid.software/en/docs/field/#custom-fields-creation)
Fields are used to generate the output of the fill and edit form template. Form elements are the building blocks of a user interface, and they allow you to create different parts of the interface and provide interaction with the user. In this section, we will cover of the most common form elements and their usage.
> Feel free to add your fields, for example, to use the convenient editor for you or any components.
[Introduction to Input](https://orchid.software/en/docs/field/#introduction-to-input)
--------------------------------------------------------------------------------------
Input is one of the most versatile form elements. It allows you to create text fields, as well as other types of input such as number, email, password, etc. Here is an example of creating a simple text input field:

Example:
use Orchid\Screen\Fields\Input;
Input::make('name');
### [Designing Input Interfaces](https://orchid.software/en/docs/field/#designing-input-interfaces)
Empty and expressionless input fields can confuse the user, but you can help by specifying a title. The title should be a short and descriptive label that clearly communicates the purpose of the field. Here is an example of how to add a title to an input field:
Input::make('name')
->title('First name');
If you need to provide additional context or instructions for the field, you can use the `help` method to add a hint or brief description. The hint should be a short and concise message that helps the user understand the purpose or format of the field. Here is an example of how to add a hint to an input field:
Input::make('name')
->help('What is your name?');
If the field requires a more detailed explanation or guidance, you can use the `popover` method to add a tooltip that will be displayed as a pop-up when the user hovers over the field. The tooltip should provide additional information or instructions that help the user complete the field correctly. Here is an example of how to add a tooltip to an input field:
Input::make('name')
->popover('Tooltip - hint that user opens himself.');
By default, form elements are displayed in a horizontal layout, with the label and input field side by side. However, you can change the layout to a vertical arrangement by using the `vertical()` method:
Input::make('name')->vertical();
If you prefer the horizontal layout, you can use the `horizontal()` method to restore it:
Input::make('name')->horizontal();
### [Required Fields](https://orchid.software/en/docs/field/#required-fields)
Sometimes you may need to specify that a field is required, meaning that the user must enter a value in the field before they can submit the form. To mark a field as required, you can use the `required()` method:
Input::make('name')
->type('text')
->required();
You can also use the `required()` method on other types of form elements, such as select, radio buttons, and checkboxes.
### [Hiding Input Fields](https://orchid.software/en/docs/field/#hiding-input-fields)
There may be times when you want to hide a form element from the user interface, either temporarily or permanently. To hide a form element, you can use the `canSee()` method and pass a value of false:
Input::make('name')->canSee(false);
If you want to show a previously hidden form element, you can use the canSee() method and pass a value of true:
Input::make('name')->canSee(true);
> Note that many methods, such as `canSee`, `required`, `title`, `help`, `vertical`, `horizontal` and many others, are available in almost every `field` of the system.
### [Types of Input](https://orchid.software/en/docs/field/#types-of-input)
One of the most universal fields is the `input` field, which allows you to specify a variety of types such as text, file, hidden, color, email, number, range, and url. The type attribute determines the kind of input field you want to create and the kind of data it will accept. Here are some examples of using the `type` method:
Input::make('name')->type('text');
A field for entering the name of the file that is sent to the server.
Input::make('name')->type('file');
Hidden field.
Input::make('name')->type('hidden');
Widget for choosing a color.
Input::make('name')->type('color');
For email addresses.
Input::make('name')->type('email');
Entering numbers.
Input::make('name')->type('number');
Slider to select numbers in the specified range.
Input::make('name')->type('range');
To specify web addresses.
Input::make('name')->type('url');
> **Please note**. Please note that support for new HTML5 attributes such as `color` and `range` is dependent on the browser being used. You can learn more about attribute types at [Mozilla’s website](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input)
> .
### [Masking Input Values](https://orchid.software/en/docs/field/#masking-input-values)
A mask is a useful tool for enforcing a specific format for user input. For example, you might want to use a mask to ensure that phone numbers are entered in a standard format, or that currency values are entered with the correct number of decimal places.
To use a mask with an input field, you can use the `mask()` method and pass a string that defines the format of the input. The string should contain placeholders for the allowed characters and any fixed characters that should be included. Here is an example of using a mask to enforce a standard phone number format:
Input::make('phone')
->mask('(999) 999-9999')
->title('Phone number');
You can also pass an array of options to the `mask()` method to customize the behavior of the mask. For example, you can use the `numericInput` option to specify that only numeric characters should be accepted:
Input::make('price')
->title('Price')
->mask([\
'mask' => '999 999 999.99',\
'numericInput' => true\
]);
You can also use the `alias` option to use a predefined mask, such as `currency`, which automatically formats the input as a currency value:
Input::make('price')
->title('Price')
->mask([\
'alias' => 'currency',\
'prefix' => ' ',\
'groupSeparator' => ' ',\
'digitsOptional' => true,\
]);
You can view all of the available options for the Inputmask library [here](https://github.com/RobinHerbots/Inputmask#options)
.
[TextArea](https://orchid.software/en/docs/field/#textarea)
------------------------------------------------------------
The `textarea` field is a form element that allows the user to enter multiple lines of text. It is similar to the input field, but it is designed to accept longer pieces of text and to preserve line breaks.
To create a `textarea` field, you can use the `TextArea` class:
use Orchid\Screen\Fields\TextArea;
TextArea::make('description');
By default, the `textarea` field will expand to fit the amount of text that is entered. However, you can use the `rows` method to specify a minimum number of rows:
TextArea::make('description')
->rows(5);
This can be useful for providing a clear visual indication of the amount of text that is expected.
As with other form elements, you can use methods such as `title()`, `help()`, and `popover()` to add additional context and guidance for the user. You can also use the `required()` method to mark the textarea field as `required` and the `canSee()` method to show or hide the field.
[CheckBox](https://orchid.software/en/docs/field/#checkbox)
------------------------------------------------------------
A checkbox is a graphical user interface element that allows the user to control a parameter with two states – checked and unchecked. Checkboxes are often used to represent binary choices, such as whether a particular feature is enabled or disabled.
To create a checkbox field, you can use the `CheckBox` class:
use Orchid\Screen\Fields\CheckBox;
CheckBox::make('free')
->value(1)
->title('Free')
->placeholder('Event for free')
->help('Event for free');
The `value` attribute determines the value that will be sent to the server when the checkbox is checked. The `title` attribute provides a label for the checkbox, and the `placeholder` attribute can be used to provide a default value or a short description. The `help` attribute can be used to provide additional context or instructions for the user.
By default, browsers do not send the value of an unchecked checkbox when the form is submitted. This can make it difficult to use checkboxes with simple Boolean values. To solve this problem, you can use the `sendTrueOrFalse()` method, which will send the value `false` to the server when the checkbox is unchecked:
CheckBox::make('enabled')
->sendTrueOrFalse();
This can be useful for ensuring that the server receives a clear indication of the state of the checkbox.
[Select](https://orchid.software/en/docs/field/#select)
--------------------------------------------------------
The select field is a form element that allows the user to choose an option from a dropdown list. It is useful for presenting a limited set of options and allowing the user to make a selection.
To create a select field, you can use the `Select` class:
use Orchid\Screen\Fields\Select;
Select::make('select')
->options([\
'index' => 'Index',\
'noindex' => 'No index',\
])
->title('Select tags')
->help('Allow search bots to index');
The `options` attribute is an array that defines the options that will be presented in the dropdown list. The keys of the array are the values that will be sent to the server, and the values are the labels that will be displayed to the user.
In addition to using an array of options, you can also use a data source to populate the options of a select field. For example, you can use a model to retrieve the options:
Select::make('user')
->fromModel(User::class, 'email');
This will retrieve all records from the `User` model and use the email field as the label for each option. You can also use a custom query to retrieve the options:
Select::make('user')
->fromQuery(User::where('balance', '!=', '0'), 'email');
This will retrieve all records from the `User` model where the `balance` field is not equal to `0`, and use the `email` field as the label for each option.
You can also specify a different field to use as the key for each option using the `fromModel()` and `fromQuery()` methods:
Select::make('user')
->fromModel(User::class, 'email', 'uuid');
This will use the `uuid` field as the key for each option, rather than the default primary key.
If you want to provide an option that represents an unselected state, you can use the `empty()` method:
// For array
Select::make('user')
->options([\
1 => 'Option 1',\
2 => 'Option 2',\
])
->empty('No select');
// For model
Select::make('user')
->fromModel(User::class, 'name')
->empty('No select');
The `empty` method also accepts the second argument, which is responsible for the value:
Select::make('user')
->empty('No select', 0)
->options([\
1 => 'Option 1',\
2 => 'Option 2',\
]);
Allow custom values with the `allowAdd` method:
Select::make('type')
->allowAdd()
->options([\
'Option 1',\
'Option 2',\
]);
[Relation](https://orchid.software/en/docs/field/#relation)
------------------------------------------------------------
Relations fields can load dynamic data, this is a good solution if you need connections.
use Orchid\Screen\Fields\Relation;
Relation::make('idea')
->fromModel(Idea::class, 'name')
->title('Choose your idea');
For multiple selections, use the `multiple()` method.
Relation::make('ideas.')
->fromModel(Idea::class, 'name')
->multiple()
->title('Choose your ideas');
> **Note.** Note the dot at the end of the name. It is necessary in order to show the expectedness of the array. As if it were `HTML` code ``
To modify the load, you can use the reference to the `scope` model, for example, take only active:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Idea extends Model
{
/**
* @param Builder $query
*
* @return Builder
*/
public function scopeActive(Builder $query)
{
return $query->where('active', true);
}
}
Relation::make('idea')
->fromModel(Idea::class, 'name')
->applyScope('active')
->title('Choose your idea');
You can also pass additional parameters to the method:
Relation::make('idea')
->fromModel(Idea::class, 'name')
->applyScope('status', 'active')
->title('Choose your idea');
You can add one or several fields, which will be additionally searched for:
Relation::make('idea')
->fromModel(Idea::class, 'name')
->searchColumns('author', 'description')
->title('Choose your idea');
To set the number of items that will be listed as a result of a search, you can chain the method chunk, passing the number of search results as a param:
Relation::make('users.')
->fromModel(User::class, 'name')
->chunk(20);
Selection options can work with calculated fields, but only to display the result, the search will occur only on one column in the database. To do this, use the `displayAppend` method.
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getFullAttribute(): string
{
return sprintf('%s (%s)', $this->name, $this->email);
}
}
To indicate the displayed field you must:
Relation::make('users.')
->fromModel(User::class, 'name')
->displayAppend('full')
->multiple()
->title('Select users');
[DateTime](https://orchid.software/en/docs/field/#datetime)
------------------------------------------------------------
The DateTime field provides a streamlined interface for selecting both date and time within your Laravel applications, leveraging the robust functionality of the `flatpickr` JavaScript library.

To create a DateTime field, utilize the `DateTimer` class:
use Orchid\Screen\Fields\DateTimer;
DateTimer::make('open')
->title('Opening date');
### [Direct Input](https://orchid.software/en/docs/field/#direct-input)
Enable direct input to allow users to manually enter:
DateTimer::make('open')
->title('Opening date')
->allowInput();
**Note:** Enabling direct input can also make the field mandatory:
DateTimer::make('open')
->title('Opening date')
->allowInput()
->required();
### [Date Format](https://orchid.software/en/docs/field/#date-format)
Customize the date format using the `format()` method:
DateTimer::make('open')
->title('Opening date')
->format('Y-m-d');
Define the format for transmitting values to the frontend with the `serverFormat()` method:
DateTimer::make('open')
->serverFormat('Y-m-d H:i:s');
Opt to display time in 24-hour format:
DateTimer::make('open')
->title('Opening date')
->format24hr();
### [Time Selection](https://orchid.software/en/docs/field/#time-selection)
Enable selection of both date and time using the `enableTime()` method:
DateTimer::make('open')
->title('Opening time')
->enableTime();
### [Time Selection Only](https://orchid.software/en/docs/field/#time-selection-only)
If only time selection is required:
DateTimer::make('open')
->title('Opening time')
->noCalendar()
->format('h:i K'); // Specify time format
### [Range Selection](https://orchid.software/en/docs/field/#range-selection)
Allow users to select a range for dates and times:
DateTimer::make('open')
->format('Y-m-d H:i')
->enableTime()
->format24hr()
->range();
### [Quick Date Selection](https://orchid.software/en/docs/field/#quick-date-selection)
Facilitate easy selection with predefined quick date options:
DateTimer::make('open')
->format('Y-m-d H:i')
->enableTime()
->format24hr()
->range()
->withQuickDates([\
'Today' => now(),\
'Yesterday' => now()->subDay(),\
'Last Week' => [now()->startOfDay()->subWeek(), now()->endOfDay()],\
]);
### [Allow Empty Values](https://orchid.software/en/docs/field/#allow-empty-values)
Allow the field to remain empty:
DateTimer::make('open')
->format('Y-m-d')
->allowEmpty()
->multiple();
### [Multiple Selection](https://orchid.software/en/docs/field/#multiple-selection)
Permit multiple date selections:
DateTimer::make('open')
->format('Y-m-d')
->allowEmpty()
->multiple();
[DateRange](https://orchid.software/en/docs/field/#daterange)
--------------------------------------------------------------
Allows you to select a range of date (and time).
Example:
use Orchid\Screen\Fields\DateRange;
DateRange::make('open')
->title('Opening between');
Default value / result is an array with keys of `start`, `end`.
DateRange::make('open')
->title('Opening between')
->value(['start' => now()->subDays(30), 'end' => now()]),
[TimeZone](https://orchid.software/en/docs/field/#timezone)
------------------------------------------------------------
The `TimeZone` field is a form element that allows the user to choose a time zone from a dropdown list. It is useful for selecting the time zone in which an event or action will take place.
use Orchid\Screen\Fields\TimeZone;
TimeZone::make('time');
This will create a dropdown list of all available time zones. You can also specify a specific set of time zones to include in the list using the `listIdentifiers()` method:
use DateTimeZone;
TimeZone::make('time')
->listIdentifiers(DateTimeZone::ALL);
The `listIdentifiers()` method takes a constant from the DateTimeZone class as an argument. The default value is `DateTimeZone::ALL`, which includes all available time zones. Other possible values are:
DateTimeZone::AFRICA;
DateTimeZone::AMERICA;
DateTimeZone::ANTARCTICA;
DateTimeZone::ARCTIC;
DateTimeZone::ASIA;
DateTimeZone::ATLANTIC;
DateTimeZone::AUSTRALIA;
DateTimeZone::EUROPE;
DateTimeZone::INDIAN;
DateTimeZone::PACIFIC;
DateTimeZone::UTC;
DateTimeZone::ALL_WITH_BC;
DateTimeZone::PER_COUNTRY;
The representation of variable zones can be found in the documentation [PHP](https://www.php.net/manual/en/class.datetimezone.php)
.
[Quill WYSIWYG Editor](https://orchid.software/en/docs/field/#quill-wysiwyg-editor)
------------------------------------------------------------------------------------
The Quill WYSIWYG (What You See Is What You Get) editor offers a seamless solution for integrating rich text editing capabilities into your web applications. With Quill, users can effortlessly insert images, apply text styling, embed videos, and more.
To create a Quill editor instance, simply utilize the `Quill` field. Here’s an example of how to implement it in your code:
use Orchid\Screen\Fields\Quill;
Quill::make('html');
### [Toolbar Controls](https://orchid.software/en/docs/field/#toolbar-controls)
Quill provides a comprehensive set of controls organized into six groups, empowering users with diverse editing functionalities. These groups include:
* **Text**: Tools for basic text formatting such as bold, italic, underline, and strikethrough.
* **Color**: Options for adjusting text and background color.
* **Header**: Tools for styling text as headers.
* **List**: Controls for creating ordered and unordered lists.
* **Format**: Additional formatting options like alignment and indentation.
* **Media**: Features for inserting multimedia content such as images and videos.
You can customize the toolbar by specifying which groups of controls to display. Here’s how you can configure the toolbar in your code:
Quill::make('html')
->toolbar(["text", "color", "header", "list", "format", "media"]);
### [Extensibility](https://orchid.software/en/docs/field/#extensibility)
One of the strengths of Quill is its extensibility through plugins. You can enhance the editor’s functionality by installing additional plugins. This can be easily accomplished using a JavaScript file.
document.addEventListener('orchid:quill', (event) => {
// Object for registering plugins
event.detail.quill;
// Parameter object for initialization
event.detail.options;
});
**Note**: You can add custom scripts and stylesheets through the `platform.php` config file
Example for [quill-image-compress](https://github.com/benwinding/quill-image-compress)
:
Add the following in `config/platform.php` into the `resource.scripts` array
"https://unpkg.com/quill-image-compress@1.2.11/dist/quill.imageCompressor.min.js",
"/js/admin/quill.imagecropper.js",
create a `quill.imagecropper.js` in `public/js/admin` with the following content
document.addEventListener('orchid:quill', (event) => {
// Object for registering plugins
event.detail.quill.register("modules/imageCompressor", imageCompressor);
// Parameter object for initialization
event.detail.options.modules = {
imageCompressor: {
quality: 0.9,
maxWidth: 1000, // default
maxHeight: 1000, // default
imageType: 'image/jpeg'
}
};
});
[Markdown Editor](https://orchid.software/en/docs/field/#markdown-editor)
--------------------------------------------------------------------------
The Markdown editor field is a powerful tool for creating and editing text using the Markdown markup language. Markdown offers a simple and intuitive syntax that allows users to focus on content creation without getting bogged down by complex formatting.
 
To create a Markdown editor field, you can use the `SimpleMDE` class:
use Orchid\Screen\Fields\SimpleMDE;
SimpleMDE::make('markdown');
[Matrix](https://orchid.software/en/docs/field/#matrix)
--------------------------------------------------------
The Matrix field provides a user-friendly interface for editing tabular data, offering flexibility and convenience. It’s particularly useful for scenarios where you need to manage structured data within a flat table format, such as storing information in a JSON column type.
You can easily create a Matrix field by specifying the column headers. Here’s an example of how to define a Matrix field with columns:
use Orchid\Screen\Fields\Matrix;
Matrix::make('options')
->columns([\
'Attribute',\
'Value',\
'Units',\
]);
### [Customizing Column Headers](https://orchid.software/en/docs/field/#customizing-column-headers)
In some cases, the values of the columns may differ from what needs to be displayed in the headers. You can address this by specifying keys for the columns:
Matrix::make('options')
->columns([\
'Attribute' => 'attr',\
'Value' => 'product_value',\
]);
### [Limiting Rows](https://orchid.software/en/docs/field/#limiting-rows)
You can also set a maximum number of rows, after which the add button will be disabled:
Matrix::make('options')
->columns(['id', 'name'])
->maxRows(10);
### [Custom Fields](https://orchid.software/en/docs/field/#custom-fields)
By default, each cell in the Matrix field contains a textarea element. However, you can customize the field types according to your requirements:
Matrix::make('users')
->title('Users list')
->columns(['id', 'name'])
->fields([\
'id' => Input::make()->type('number'),\
'name' => TextArea::make(),\
]);
> It’s important to note that the Matrix field performs field copying on the client side. While this works seamlessly for simple input and select fields, it may encounter limitations with complex or compound fields.
[Code editor](https://orchid.software/en/docs/field/#code-editor)
------------------------------------------------------------------
A field for writing program code with the ability to highlight.

Example:
use Orchid\Screen\Fields\Code;
Code::make('code');
To specify code highlighting for a specific programming language, you can use the `language()` method.
Code::make('code')
->language(Code::CSS);
The following languages are available:
* Markup – `markup`, `html`, `xml`, `svg`, `mathml`
* CSS – `css`
* C-like – `clike`
* JavaScript – `javascript`, `js`
The number of lines is supported:
Code::make('code')
->lineNumbers();
[Picture](https://orchid.software/en/docs/field/#picture)
----------------------------------------------------------
Allows you to upload an image.
Example:
use Orchid\Screen\Fields\Picture;
Picture::make('picture');
You can specify the storage backend for the uploaded image using the `storage` method:
Picture::make('picture')
->storage('s3');
Use the `acceptedFiles` method to define the types of files that the field should accept. This is done using unique [unique file type specifiers](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers)
.
For example, to only allow JPEG images, you can use the following code:
Picture::make('picture')
->acceptedFiles('.jpg');
[Cropper](https://orchid.software/en/docs/field/#cropper)
----------------------------------------------------------
Extends Picture and allows you to upload an image and crop to the desired format.

Example:
use Orchid\Screen\Fields\Cropper;
Cropper::make('picture');
### [Width and Height](https://orchid.software/en/docs/field/#width-and-height)
In order to control the format, you can specify the width and height of the desired image:
Cropper::make('picture')
->width(500)
->height(300);
Or you can impose specific limits using `minWidth` / `maxWidth` or `minHeight` / `maxHeight` or use convenience methods `minCanvas` / `maxCanvas`
Cropper::make('picture')
->minCanvas(500)
->maxWidth(1000)
->maxHeight(800);
### [File Size Limit](https://orchid.software/en/docs/field/#file-size-limit)
To limit the size of the downloaded file, you must set the maximum value in `MB`.
Cropper::make('picture')
->maxFileSize(2);
### [Value](https://orchid.software/en/docs/field/#value)
The control of the return value is carried out using the methods:
Cropper::make('picture')
->targetId();
The sequence number (`id`) of the `Attachment` record will be returned.
Cropper::make('picture')
->targetRelativeUrl();
Will return the relative path to the image.
Cropper::make('picture')
->targetUrl();
Will return the absolute path to the image.
[Attach](https://orchid.software/en/docs/field/#attach)
--------------------------------------------------------
The `Attach` field provides an intuitive interface for uploading images and files, including support for grouping and sorting.
To create a file upload element, use the `make` method of the `Attach` class and specify the field name:
use Orchid\Screen\Fields\Attach;
Attach::make('attachments');
To allow multiple file uploads, use the `multiple()` method:
Attach::make('attachments')
->multiple();
### [File Upload Limitations](https://orchid.software/en/docs/field/#file-upload-limitations)
For multiple file uploads, you can set a maximum number of files that can be uploaded using the `maxCount` method:
Attach::make('attachments')
->multiple()
->maxCount(3); // 3 files
You can also limit the file size using the `maxSize()` method. The size is specified in megabytes (MB):
Attach::make('attachments')
->maxSize(1024); // Size in MB
> **Maximum file upload size:** By default, the values for `upload_max_filesize` and `post_max_size` are set to 2M. You can change these settings in `php.ini` to allow file uploads larger than 2M.
Use the `accept` method to specify which file types the field should accept, for example:
Attach::make('upload')
->accept('image/*,application/pdf,.psd');
The provided string is a list of [unique file type specifiers](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers)
, separated by commas.
### [File Grouping](https://orchid.software/en/docs/field/#file-grouping)
You can group files by different categories using the `group` method. This is particularly useful if you need to upload different types of files, such as documents and images.
Attach::make('docs')
->group('documents');
Attach::make('images')
->group('photo');
To work with uploaded files that are grouped through model relationships, use the following syntax:
use Orchid\Attachment\Models\Attachment;
/**
* Returns the attached "hero" (one-to-one).
*/
public function hero(): HasOne
{
return $this->hasOne(Attachment::class, 'id', 'hero')
->withDefault();
}
/**
* Returns documents (many-to-many).
* Upload is handled via the group() method.
*/
public function documents(): MorphToMany
{
return $this->attachments('documents');
}
### [File Storage](https://orchid.software/en/docs/field/#file-storage)
The upload field can work with different repositories. To do this, specify the repository key defined in `config/filesystems.php`:
Attach::make('upload')
->storage('s3');
By default, the `public` storage is used.
### [Explicit File Path Configuration](https://orchid.software/en/docs/field/#explicit-file-path-configuration)
If you need to override the standard file storage rules and explicitly define the upload path, use the `path` method:
Attach::make('upload')
->path('/custom/path');
### [File Validation and Sorting on the Server](https://orchid.software/en/docs/field/#file-validation-and-sorting-on-the-server)
It’s important to validate files on the server side. For example, check that the file is an image with a specific aspect ratio or file type. To do this, use the `uploadUrl` method to specify the endpoint for file uploads:
Attach::make('upload')
->uploadUrl(route('my.upload.endpoint'));
Similarly, you can specify an endpoint for sorting files:
Attach::make('upload')
->sortUrl(route('my.sort.endpoint'));
### [Error Handling and Message Display](https://orchid.software/en/docs/field/#error-handling-and-message-display)
To ensure that users don’t encounter unclear errors, it’s important to provide clear and informative error messages. Use the `errorMaxSizeMessage` and `errorTypeMessage` methods to specify custom messages:
Attach::make('upload')
->errorMaxSizeMessage("File size is too large")
->errorTypeMessage("Invalid file type");
[Group](https://orchid.software/en/docs/field/#group)
------------------------------------------------------
The `Group` component is used to combine multiple fields into a single line, allowing for more compact and organized interfaces. This is especially useful for grouping related data, such as first and last names.
Group::make([\
Input::make('first_name'),\
Input::make('last_name'),\
]),
### [Column Width](https://orchid.software/en/docs/field/#column-width)
By default, fields will take up the full available width of the screen when you use the `fullWidth` method. This option is suitable for most scenarios where you need elements to fill the entire space:
Group::make([\
// ...\
])->fullWidth();
However, there may be cases where you want fields to occupy only the necessary space. The `autoWidth` method is perfect for situations where fields contain varying amounts of data. For example, when using radio buttons:
Group::make([\
Radio::make('agreement')\
->placeholder('Yes')\
->value(1),\
\
Radio::make('contact')\
->placeholder('No')\
->value(0),\
])->autoWidth();
For greater flexibility in configuring column widths, you can use the `widthColumns()` method, which supports CSS Grid. This method allows you to specify column widths using values for the `grid-template-columns` property:
Group::make([\
// ...\
])->widthColumns('2fr 1fr');
Accepted values for `widthColumns()` include:
* Percentages (e.g., `30%`)
* Pixels (e.g., `120px`)
* Fractional units (e.g., `2fr`)
* Other values such as `max-content` and `auto`
> **Important:** The number of specified values must not be less than the number of elements in the group.
The width settings apply only on desktop devices. On mobile devices, each field will be displayed on a new line, enhancing the responsiveness of the interface and improving user experience.
### [Column Alignment](https://orchid.software/en/docs/field/#column-alignment)
Columns within a group can have different heights, especially when a header is present in only one of them. To create a more visually appealing interface, it is essential to utilize column alignment.
When one of the columns has a header, aligning all columns to the bottom of the parent container will create a more harmonious look. To achieve this, use the `alignEnd` method:
Group::make([\
// ...\
])->alignEnd();
If you want all elements to align at the top, apply the `alignStart` method:
Group::make([\
// ...\
])->alignStart();
To ensure that the columns are aligned along the baseline of the text for consistency in content display, use the `alignBaseLine` method:
Group::make([\
// ...\
])->alignBaseLine();
For a symmetrical appearance, center the columns using the `alignCenter` method:
Group::make([\
// ...\
])->alignCenter();
[Button](https://orchid.software/en/docs/field/#button)
--------------------------------------------------------
Buttons are used to submit a form filled out by the user to the server.
To create a button that calls the `handler` method defined in the current screen, use `Button::make()`:
Button::make('Submit')
->method('handler');
> The method must be available in the screen where the button is located.
If you need to pass specific data to the method, specify it as the second argument:
Button::make('Submit')
->method('handler', [\
'user' => 1,\
]);
### [Action Confirmation](https://orchid.software/en/docs/field/#action-confirmation)
To prevent accidental actions, add the `confirm()` method. This will display a confirmation dialog before executing the action. It is particularly useful for irreversible actions, such as data deletion.
Button::make('Delete')
->method('deleteItem')
->confirm('You will lose access to this item.');
> **Tip:** Use clear and concise messaging in `confirm()` so the user understands the consequences.
### [Submission URL](https://orchid.software/en/docs/field/#submission-url)
To specify the URL where the form data should be sent, use the `action()` method. Typically, this will be the URL of a controller within your application where the request is processed after the button is clicked.
Button::make('Submit')
->action('https://orchid.software');
Button::make('Submit')
->action(route('controller.method'));
### [File Download](https://orchid.software/en/docs/field/#file-download)
To initiate a file download when clicking a button, use the `download()` method. This signals the system that the result of the method execution will be a downloadable file rather than simply displaying it in the browser.
Button::make('Download Report')
->method('export')
->download();
[Link](https://orchid.software/en/docs/field/#link)
----------------------------------------------------
Links (`Link`) are used to direct the user to another page or to perform an action, such as downloading a file.
To create a link to a specific URL, use `Link::make()` with the link text and the `href()` method:
Link::make('Visit Orchid')
->href('https://orchid.software');
### [Opening Link in a New Tab](https://orchid.software/en/docs/field/#opening-link-in-a-new-tab)
To open a link in a new tab, add the `target('_blank')` method. This is useful for external sites or resources you want to open alongside the current page.
Link::make('Documentation')
->href('https://orchid.software/docs')
->target('_blank');
### [File Download](https://orchid.software/en/docs/field/#file-download)
If the link should initiate a file download, use the `download()` method. This informs the browser that the link points to a downloadable file.
Link::make('Download Report')
->href('/path/to/report.pdf')
->download();
> **Note:** Ensure the file is accessible at the specified path to avoid download errors.
[Dropdown Menu](https://orchid.software/en/docs/field/#dropdown-menu)
----------------------------------------------------------------------
The `Dropdown` component allows you to create a button with a dropdown list of actions, which is convenient for grouping related actions, such as a three-dot menu for managing an item.
To create a dropdown menu, list all actions in the `list()` method:
DropDown::make()
->icon('bs.options-vertical')
->list([\
Link::make('Edit')\
->route('platform.systems.users.edit', $user->id),\
\
Button::make('Delete')\
->method('remove')\
->icon('trash'),\
]);
[NumberRange](https://orchid.software/en/docs/field/#numberrange)
------------------------------------------------------------------
You can create ranges of numbers. Especially useful for filters.
NumberRange::make();
Usage with filters:
TD::make()->filter(NumberRange::make());
//or
TD::make()->filter(TD::FILTER_NUMBER_RANGE);
Result is an array with keys of `min`, `max`.
[Custom Fields Creation](https://orchid.software/en/docs/field/#custom-fields-creation)
----------------------------------------------------------------------------------------
To create custom fields, refer to the “Builder” page in the documentation. This page provides a straightforward guide on how to create and customize fields according to your requirements. Access the “Builder” page by clicking here: [Builder](https://orchid.software/en/docs/builder)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Eloquent Filters | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/filters/# "Scroll to the top of the page")
Eloquent Filters
================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/filters.md "View and edit this file on GitHub")
* [Introduction](https://orchid.software/en/docs/filters/#introduction)
* [Using Filters for Different Models](https://orchid.software/en/docs/filters/#using-filters-for-different-models)
* [Running the Filter Always](https://orchid.software/en/docs/filters/#running-the-filter-always)
* [Parameter Patterns](https://orchid.software/en/docs/filters/#parameter-patterns)
* [Customizing Filter Display Values](https://orchid.software/en/docs/filters/#customizing-filter-display-values)
* [Selection](https://orchid.software/en/docs/filters/#selection)
* [Displaying on a Screen](https://orchid.software/en/docs/filters/#displaying-on-a-screen)
* [Customization with Templates](https://orchid.software/en/docs/filters/#customization-with-templates)
* [Handling HTTP Parameters](https://orchid.software/en/docs/filters/#handling-http-parameters)
* [Filtering](https://orchid.software/en/docs/filters/#filtering)
* [Query Examples](https://orchid.software/en/docs/filters/#query-examples)
* [Sorting](https://orchid.software/en/docs/filters/#sorting)
* [Default Sorting](https://orchid.software/en/docs/filters/#default-sorting)
[Introduction](https://orchid.software/en/docs/filters/#introduction)
----------------------------------------------------------------------
Eloquent Filters are powerful tools for creating complex queries in Laravel. They allow you to easily manage and customize your search criteria. You can use Eloquent filters to filter your product catalog based on attributes, brands, and other criteria.
To create a new Eloquent filter, you can use the `php artisan orchid:filter` command followed by the desired filter name. This command will generate a new filter class in the `app/Orchid/Filters` folder.
Here’s an example of creating an `EmailFilter`:
php artisan orchid:filter EmailFilter
The generated filter class will look like this:
namespace App\Http\Filters;
use Orchid\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class EmailFilter extends Filter
{
/**
* The array of matched parameters.
*
* @var array
*/
public $parameters = ['email'];
/**
* Apply filter if the request parameters were satisfied.
*
* @param Builder $builder
*
* @return Builder
*/
public function run(Builder $builder): Builder
{
return $builder->where('email', $this->request->get('email'));
}
/**
* Get the display fields.
*
* @return Field[]
*/
public function display(): array
{
return [\
Input::make('email')\
->type('text')\
->value($this->request->get('email'))\
->placeholder('Search...')\
->title('Search')\
];
}
}
To use filters in your own models, you need to connect the trait `Orchid\Filters\Filterable` and pass an array of classes to the `filters` function:
use App\Model;
Model::filters([EmailFilter::class])->simplePaginate();
### [Using Filters for Different Models](https://orchid.software/en/docs/filters/#using-filters-for-different-models)
One of the great advantages of filters is that you can reuse the same filter class for different models. This allows you to define a filter once and apply it to multiple models, reducing code duplication. Simply specify the filter class when applying filters to your models:
$filters = [\
EmailFilter::class,\
];
User::filters($filters)
->simplePaginate();
Customer::filters($filters)
->simplePaginate();
### [Running the Filter Always](https://orchid.software/en/docs/filters/#running-the-filter-always)
By default, filters are applied only when the corresponding parameters are specified. However, if you want a filter to run on every request, you can leave the `$parameters` property as an empty array in your filter class. This way, the filter will be applied to all queries. For instance:
public $parameters = [];
Additionally, if the array returned by the `display` method is empty, the filter will not appear in the interface but will still remain functional in queries. This allows for flexible configurations where certain filters operate silently in the background.
### [Parameter Patterns](https://orchid.software/en/docs/filters/#parameter-patterns)
Filter provides the capability to define parameter patterns using a convenient syntax. This allows you to create custom patterns and perform advanced filtering based on specific patterns. For example:
/**
* The array of matched parameters.
*
* @var null|array
*/
public $parameters = [\
'pattern.*',\
];
In the above example, the filter will match any parameter that follows the pattern `pattern.*`. This allows you to handle a wide range of dynamic parameters in your filters.
### [Customizing Filter Display Values](https://orchid.software/en/docs/filters/#customizing-filter-display-values)
By default, the filter value is displayed in the format `name:value`, which works well for a wide range of filters. However, when dealing with IDs or system names, you might prefer to display a more user-friendly value.
To achieve this, you can define a `value` method that returns a string. For example:
public function value(): string
{
return 'Your custom value';
}
If the filter is applied, this string will be displayed in the user interface.
This approach is particularly useful when using filters that rely on IDs or system-specific names, allowing you to provide more meaningful or descriptive output for the end user.
[Selection](https://orchid.software/en/docs/filters/#selection)
----------------------------------------------------------------
The “Selection” layer provides a convenient way to group and organize filters for both displaying and applying them to a model. This layer acts as an intermediary between the user interface and the model, simplifying the process of managing filters.
To create a “Selection” layer, you can use the following command:
php artisan orchid:selection MailingSelection
This command will generate a new PHP file called `MailingSelection` in the `App\Orchid\Layouts` directory. Inside this class, you will find a single method called `filters()`. This method is where you should list all the filters that need to be displayed and applied.
For example, let’s say you want to display and apply two filters: a email filter and a created filter. Your `MailingSelection` class would look like this:
namespace App\Orchid\Layouts;
use App\Orchid\Filters\EmailFilter;
use App\Orchid\Filters\CreatedFilter;
use Orchid\Screen\Layouts\Selection;
class MailingSelection extends Selection
{
/**
* @return Filter[]
*/
public function filters(): array
{
return [\
EmailFilter::class,\
CreatedFilter::class\
];
}
}
Once you have defined your filters in the `MailingSelection` class, you can apply them to a model by using the `filters()` method. For example:
Model::filters(MailingSelection::class)->simplePaginate();
By calling the `filters()` method on your model and passing `MailingSelection::class` as the argument, you can apply the filters defined in the `MailingSelection` class to the model.
### [Displaying on a Screen](https://orchid.software/en/docs/filters/#displaying-on-a-screen)
The “Selection” layer can also be used to display filters on a [screen](https://orchid.software/en/docs/screens)
. In the `layout()` method of your screen, you can include the `MailingSelection` class to display the filters on the screen. For example:
use App\Orchid\Layouts\MailingSelection;
public function layout(): array
{
return [\
MailingSelection::class,\
];
}
> Please note that filters with empty fields will not be rendered, ensuring a clean and user-friendly interface.
### [Customization with Templates](https://orchid.software/en/docs/filters/#customization-with-templates)
The appearance of the selection layer can vary, such as being displayed as a drop-down list (the default) or as a form. You can define this using the `template` property. For instance:
class MailingSelection extends Selection
{
/**
* Template for rendering the selection.
*
* You can use any Blade template. Defaults:
* - `self::TEMPLATE_LINE` for a linear layout
* - `self::TEMPLATE_DROP_DOWN` for a dropdown menu
*/
public $template = self::TEMPLATE_DROP_DOWN;
/**
* @return Filter[]
*/
public function filters(): array
{
return [\
//...\
];
}
}
Moreover, you have the flexibility to define your own `Blade` template within this property.
[Handling HTTP Parameters](https://orchid.software/en/docs/filters/#handling-http-parameters)
----------------------------------------------------------------------------------------------
To automatically filter and sort your application’s data based on user-supplied HTTP parameters, the package provides a powerful and flexible set of tools. The key to effectively utilizing these tools is to ensure that your model includes the `Filterable` trait and implements a whitelist of acceptable filter and sort parameters.
To make your `App\Models\Post` model filterable, follow these steps:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Orchid\Filters\Filterable;
use Orchid\Filters\Types\Like;
use Orchid\Filters\Types\Where;
use Orchid\Filters\Types\WhereDate;
use Orchid\Filters\Types\WhereMaxMin;
use Orchid\Filters\Types\WhereDateStartEnd;
class Post extends Model
{
use Filterable;
}
### [Filtering](https://orchid.software/en/docs/filters/#filtering)
As mentioned before, any filtering action can only be performed on an allowed list of filters, which is specified using the `allowedFilters` property as a key-value pair. The key represents the name of your columns, and the value is the handling class. Here’s an example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Orchid\Filters\Filterable;
use Orchid\Filters\Types\Like;
use Orchid\Filters\Types\Where;
use Orchid\Filters\Types\WhereDate;
use Orchid\Filters\Types\WhereMaxMin;
use Orchid\Filters\Types\WhereDateStartEnd;
class Post extends Model
{
use Filterable;
/**
* The attributes for which you can use filters in url.
*
* @var array
*/
protected $allowedFilters = [\
'id' => Where::class,\
'user_id' => WhereIn::class,\
'rating' => WhereMaxMin::class,\
'content' => Like::class,\
'publish_at' => WhereDate::class,\
'created_at' => WhereDateStartEnd::class,\
'deleted_at' => WhereDateStartEnd::class,\
];
}
Once you have specified the list, using automatic filtering is straightforward. Simply call the `filters()` method, for example:
Post::filters()->paginate();
By leveraging this approach, you can easily apply filters to your query and paginate the results.
This code will automatically apply any filters or sorting rules that were included in the user’s HTTP request.
#### [Query Examples](https://orchid.software/en/docs/filters/#query-examples)
In order to use this feature effectively, it’s important to have a solid understanding of how the HTTP parameters are translated into database queries. For example:
http://example.com/demo?filter[id]=1
$model->where('id', '=', 1)
This query will apply a `where` clause to the `id` column of your model, filtering out any records that don’t match the value provided by the user.
http://example.com/demo?filter[name]=A
$model->where('name', 'like', '%A%')
This query will apply a `like` clause to the `name` column of your model, searching for any records that contain the letter “A” in their name.
http://example.com/demo?filter[id]=1,2,3,4,5
$model->whereIn('id', [1,2,3,4,5]);
This query will apply a `wherein` clause to the `id` column of your model, filtering for any records that match one of the specified IDs.
http://example.com/demo?filter[id][min]=1&filter[id][max]=5
$model->whereBetween('id', [1,5]);
This query will apply a `wherebetween` clause to the `id` column of your model, filtering for records where the ID is between 1 and 5.
http://example.com/demo?filter[id][]=1&filter[id][]=2&filter[id][]=3
$model->whereIn('id', [1,2,3]);
This query will apply a `whereIn` clause to the `id` column of your model, filtering for records where the ID is one of the specified values.
http://example.com/demo?filter[rating][min]=1&filter[rating][max]=5
$model->where('rating', '>=', 1)
->where('rating', '<=', 5);
This query will apply two separate `where` clauses to the `rating` column of your model, filtering for records where the rating is between 1 and 5.
http://example.com/demo?filter[rating][min]=1
$model->where('rating', '>=', 1);
This query will apply a single `where` clause to the `rating` column of your model, filtering for records where the rating is greater than or equal to 1.
http://example.com/demo?filter[publish_at]=2023-02-02
$model->where('publish_at', '2023-02-02')
This query will apply a single `where` clause to the `publish_at` column of your model, filtering for records where the `publish_at` date is exactly equal to February 2, 2023.
http://example.com/demo?filter[created_at][start]=2023-01-01&filter[created_at][end]=2023-02-02
$model->whereDate('created_at', '>=', '2023-01-01')
->whereDate('created_at', '<=', '2023-02-02');
This query will apply two separate `whereDate` clauses to the `created_at` column of your model, filtering for records where the `created_at` date falls within the specified range.
http://example.com/demo?filter[created_at][start]=2023-01-01
$model->whereDate('created_at', '>=', '2023-01-01')
This query will apply a single `whereDate` clause to the `created_at` column of your model, filtering for records where the `created_at` date is greater than or equal to January 1, 2023.
> HTTP filters or sorting do not have separate display templates. You can see an example of this [use in the table headers](https://orchid.software/en/docs/table/#sorting)
> .
### [Sorting](https://orchid.software/en/docs/filters/#sorting)
To enable sorting functionality, you need to specify a list of columns in the `allowedSorts` property. This list represents the columns in your database table that can be used for sorting. Here’s an example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Orchid\Filters\Filterable;
class Post extends Model
{
use Filterable;
/**
* The attributes for which can use sort in url.
*
* @var array
*/
protected $allowedSorts = [\
'id',\
'user_id',\
'rating',\
'publish_at',\
'created_at',\
'deleted_at',\
];
}
Once you have defined the allowed sortable columns, you can easily enable sorting by calling the `filters()` method. This method will handle the sorting based on the provided HTTP parameter. For instance:
Post::filters()->paginate();
Now, when you make an HTTP request, the sorting behavior will be as follows:
http://example.com/demo?sort=created_at
$model->orderBy('created_at', 'asc');
http://example.com/demo?sort=-created_at
$model->orderBy('created_at', 'desc');
### [Default Sorting](https://orchid.software/en/docs/filters/#default-sorting)
If you want to specify a default sorting order for your data, you can use the `defaultSort` method. This method allows you to set a default column for sorting when no specific sorting parameter is provided via the HTTP request. For example:
Post::filters()->defaultSort('id')->paginate();
You can also specify the sort direction as a second parameter. For instance:
Post::filters()->defaultSort('id', 'desc')->paginate();
Automatic sorting and filtering of HTTP requests will not work with fields of models obtained through relationships. If you need sorting or filtering based on such fields, you can use third-party packages, such as [Eloquent Power Joins](https://github.com/kirschbaum-development/eloquent-power-joins)
. This package can help you solve this issue:
User::orderByPowerJoins('profile.city');
User::orderByPowerJoins('profile.city', 'desc');
However, you will need to manually handle the HTTP parameters `sort` and `filter`, as the package does not automatically recognize that the `-` sign before the field name indicates descending order for sorting, and also how to apply filters. You can do this using a “Filter.” Additionally, you should only use the package methods for sorting or filtering based on fields accessible through relationships.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Global Search | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/global-search/# "Scroll to the top of the page")
Global Search
=============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/global-search.md "View and edit this file on GitHub")
* [Using Full-Text Search](https://orchid.software/en/docs/global-search/#using-full-text-search)
* [Customizing Search Queries](https://orchid.software/en/docs/global-search/#customizing-search-queries)
[Using Full-Text Search](https://orchid.software/en/docs/global-search/#using-full-text-search)
------------------------------------------------------------------------------------------------
Orchid provides full-text search capabilities through the [Laravel Scout](https://github.com/laravel/scout)
package. This package offers an abstraction for searching through your `Eloquent` models and requires that you specify the search driver that you will use for your application. These can be elasticsearch, algolia, sphinx, or other solutions.
To make your models searchable within the application, you must register them in the Orchid [configuration file](https://orchid.software/en/docs/configuration)
. You can do this by adding a new entry to the 'search’ array for each model you want to make searchable. For example:
'search' => [\
\App\Models\Idea::class,\
],
> This example uses [presenters](https://orchid.software/en/docs/presenters)
> , it is highly recommended that you familiarize yourself with them. And also, take steps to configure the model from the documentation [Laravel Scout](https://github.com/laravel/scout)
> .
The [Presenter](https://orchid.software/en/docs/presenters)
is used to display the search results, which calls the `presenter()` method of the model:
namespace App;
use App\Orchid\Presenters\IdeaPresenter;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Idea extends Model
{
use Searchable;
/**
* Get the presenter for the model.
*
* @return IdeaPresenter
*/
public function presenter()
{
return new IdeaPresenter($this);
}
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
$array = $this->toArray();
// Customize array...
return $array;
}
}
In the representatives, we indicate the `Searchable` interface and define methods that will return values for a display to the user, for example like this:
namespace App\Orchid\Presenters;
use Laravel\Scout\Builder;
use Orchid\Screen\Contracts\Searchable;
use Orchid\Support\Presenter;
class IdeaPresenter extends Presenter implements Searchable
{
/**
* @return string
*/
public function label(): string
{
return 'Ideas';
}
/**
* @return string
*/
public function title(): string
{
return $this->entity->name;
}
/**
* @return string
*/
public function subTitle(): string
{
return 'Small descriptions';
}
/**
* @return string
*/
public function url(): string
{
return url('/');
}
/**
* @return string
*/
public function image(): ?string
{
return null;
}
/**
* @param string|null $query
*
* @return Builder
*/
public function searchQuery(string $query = null): Builder
{
return $this->entity->search($query);
}
/**
* @return int
*/
public function perSearchShow(): int
{
return 3;
}
}
[Customizing Search Queries](https://orchid.software/en/docs/global-search/#customizing-search-queries)
--------------------------------------------------------------------------------------------------------
To customize search queries, you can override the default `searchQuery()` method. This method returns a `Builder` instance representing the query used to index the model.
public function searchQuery(string $query = null): Builder
{
return $this->entity->search($query)->where('active', true);
}
Here, in the `searchQuery()` method, the `where()` method was used to limit the search to only active models
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Layers for Grouping | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/grouping/# "Scroll to the top of the page")
Layers for Grouping
===================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/grouping.md "View and edit this file on GitHub")
* [Split](https://orchid.software/en/docs/grouping/#split)
* [Customizing the Ratio](https://orchid.software/en/docs/grouping/#customizing-the-ratio)
* [Reversing the Order on Mobile](https://orchid.software/en/docs/grouping/#reversing-the-order-on-mobile)
* [Sortable](https://orchid.software/en/docs/grouping/#sortable)
* [Preparing the Database](https://orchid.software/en/docs/grouping/#preparing-the-database)
* [Preparing the Eloquent Model](https://orchid.software/en/docs/grouping/#preparing-the-eloquent-model)
* [Usage in a Screen](https://orchid.software/en/docs/grouping/#usage-in-a-screen)
* [Columns](https://orchid.software/en/docs/grouping/#columns)
* [TabMenu](https://orchid.software/en/docs/grouping/#tabmenu)
* [Tabs](https://orchid.software/en/docs/grouping/#tabs)
* [Accordion](https://orchid.software/en/docs/grouping/#accordion)
[Split](https://orchid.software/en/docs/grouping/#split)
---------------------------------------------------------
Allows you to divide the screen into two customizable sections. This layout is particularly useful when you want to display two separate pieces of information side-by-side.
Orchid provides a shortcut method for creating a Split layout with two views using the `Layout::split()` method. To create a Split layout, simply pass an array of two Layout objects as the first parameter to the `split()` method. You can also set the ratio of the two sections using the optional `ratio()` method as the second parameter.
Here’s an example of how to create a Split layout:
use Orchid\Support\Facades\Layout;
Layout::split([\
Layout::view('first-view'),\
Layout::view('second-view'),\
]);
### [Customizing the Ratio](https://orchid.software/en/docs/grouping/#customizing-the-ratio)
By default, the Split layout divides the screen with a `50/50` ratio. However, you can easily customize this ratio using the `ratio()` method. This method takes a string argument that specifies the desired ratio. Here are the valid ratios:
* 20/80
* 30/70
* 40/60
* 50/50
* 60/40
* 70/30
* 80/20
For example, to create a `Split` layout with a `40/60` ratio:
use Orchid\Support\Facades\Layout;
Layout::split([\
Layout::view('first-view'),\
Layout::view('second-view'),\
])->ratio('40/60'),
### [Reversing the Order on Mobile](https://orchid.software/en/docs/grouping/#reversing-the-order-on-mobile)
By default, the order of the two sections in a `Split` layout is fixed. However, you can reverse the order of the sections on mobile devices by calling the `reverseOnPhone()` method. Here’s an example:
use Orchid\Support\Facades\Layout;
Layout::split([\
Layout::view('first-view'),\
Layout::view('second-view'),\
])->ratio('40/60')->reverseOnPhone(),
This will create a `Split` layout with a `40/60` ratio, and the order of the sections will be reversed on mobile devices.
[Sortable](https://orchid.software/en/docs/grouping/#sortable)
---------------------------------------------------------------
Sortable in the Orchid platform simplifies managing the order of elements in your application. You will be able to easily change the order of items in your list and create interactive user interfaces through a simple drag and drop function. This significantly facilitates working with ordered elements in the user interface.
### [Preparing the Database](https://orchid.software/en/docs/grouping/#preparing-the-database)
To start using the sorting functionality, you need to prepare the database. To do this, create a migration that adds a simple integer column to the table you plan to work with. Here’s an example migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOrderColumnToTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->integer('order')->default(1);
});
}
// ...
}
Replace `table_name` with the name of the table to which you want to add the column. You can also choose any other name for the column by replacing `'order'` with the preferred name.
> Don’t forget to run the migration using the `php artisan migrate` command to add the new column to the database.
### [Preparing the Eloquent Model](https://orchid.software/en/docs/grouping/#preparing-the-eloquent-model)
After setting up the database and migrations, add the `Sortable` trait to your model:
use Illuminate\Database\Eloquent\Model;
use Orchid\Platform\Concerns\Sortable;
class Idea extends Model
{
use Sortable;
//...
}
> Note: Make sure to import the Eloquent model class and then use the `Sortable` trait.
If the column name is different from `order`, you can add a `getSortColumnName()` method to your model to explicitly specify the column name:
use Illuminate\Database\Eloquent\Model;
use Orchid\Platform\Concerns\Sortable;
class Idea extends Model
{
use Sortable;
//...
/**
* Get the column name for sorting.
*
* @return string
*/
public function getSortColumnName(): string
{
return 'sort';
}
}
### [Usage in a Screen](https://orchid.software/en/docs/grouping/#usage-in-a-screen)
Now we have a prepared model with sorting functionality. Let’s create a graphical interface for drag and drop sorting. In the `query()` method of your screen, specify the list of models that will be displayed for sorting:
use App\Models\Idea;
use Orchid\Screen\Repository;
public function query(): array
{
return [\
'models' => Idea::sorted()->get(),\
];
}
Here, we use the `sorted()` method provided by the `Sortable` trait to get a sorted list of models. It also has an optional argument for sorting direction (ASC – ascending, DESC – descending). By default, the value is set to ASC.
In the `layout()` method of your screen, add the graphical interface using the `Layout::sortable()` layer:
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Sight;
public function layout(): iterable
{
return [\
Layout::sortable('models', [\
Sight::make('title'),\
]),\
];
}
[Columns](https://orchid.software/en/docs/grouping/#columns)
-------------------------------------------------------------
Columns are useful when you want to group content horizontally. They allow you to divide the layout into multiple columns of equal width, which can be used to display content side by side.
> Columns differ from `Split` in that they always have the same width and there can be many of them.
Here is an example of columns:

To create columns in Orchid, you can use the `Layout::columns()` method. This method accepts an array of content, which will be displayed in the columns.
Here is an example of how to create columns using the short syntax:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::columns([\
UserProfileForm::class,\
ContactInformationForm::class,\
]),\
];
}
In the example above, the layout is divided into two columns, and the content of each column is specified as the lowercase name of a class.
[TabMenu](https://orchid.software/en/docs/grouping/#tabmenu)
-------------------------------------------------------------
The `TabMenu` layout allows you to display navigation items visually similar to tabs, but instead of switching between tabs, clicking on an item will navigate to a different screen.
To create a `TabMenu` layout, you can use the `artisan` command:
php artisan orchid:tab-menu ExampleNavigation
This will create a new class called `ExampleNavigation` in the `app/Orchid/Layouts` directory. You can define the navigation items in this class by implementing the `navigations` method:
namespace App\Orchid\Layouts;
use Orchid\Screen\Actions\Menu;
use Orchid\Screen\Layouts\TabMenu;
class ExampleNavigation extends TabMenu
{
/**
* Get the menu elements to be displayed.
*
* @return Menu[]
*/
protected function navigations(): iterable
{
return [\
Menu::make('Get Started')\
->route('platform.main'),\
];
}
}
You can specify the items in the same way as in the [Menu section](https://orchid.software/en/docs/menu)
use App\Orchid\Layouts\ExampleNavigation;
public function layout(): array
{
return [\
ExampleNavigation::class\
];
}
[Tabs](https://orchid.software/en/docs/grouping/#tabs)
-------------------------------------------------------
Tabs group content and help with navigation. Useful when you want to switch between hiding and displaying a some of content:

Tabs support short syntax by calling a static method, which does not require creating a separate class:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => [\
Layout::rows([\
Input::make('user.name')\
->type('text')\
->required()\
->title('Name')\
->placeholder('Name'),\
\
Input::make('user.email')\
->type('email')\
->required()\
->title('Email')\
->placeholder('Email'),\
]),\
],\
'Billing Address' => [\
Layout::rows([\
Input::make('address')\
->type('text')\
->required(),\
]),\
],\
]),\
];
}
Keys will be used as headers.
Please note that you can specify the lowercase name of the class as values:
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
]),\
];
}
By default, the active tab will be either the first or the last active one. If you need to define the active tab explicitly, you can do this using the `->activeTab($key)` method
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
])->activeTab('Billing Address'),\
];
}
[Accordion](https://orchid.software/en/docs/grouping/#accordion)
-----------------------------------------------------------------
Accordions are useful when you want to switch between hiding and displaying a lot of content in a compact space. They consist of a series of collapsible panels, each containing a header and content. When a panel is expanded, its content becomes visible, while the other panels are collapsed.
Here is an example of an accordion:

To create an accordion in Orchid, you can use the `Layout::accordion()` method. This method accepts an array of panel names and content, where the keys of the array will be used as the panel headers and the values will be used as the panel content.
Here is an example of how to create an accordion using the short syntax:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::accordion([\
'Personal Information' => [\
Layout::rows([\
Input::make('user.name')\
->type('text')\
->required()\
->title('Name')\
->placeholder('Name'),\
\
Input::make('user.email')\
->type('email')\
->required()\
->title('Email')\
->placeholder('Email'),\
]),\
],\
'Billing Address' => [\
Layout::rows([\
Input::make('address')\
->type('text')\
->required(),\
]),\
],\
]),\
];
}
In the example above, the accordion has two panels: “Personal Information” and “Billing Address”. The content of each panel is specified as an array of rows created using the `Layout::rows()` method.
You can also specify the content of each panel as the lowercase name of a class that returns an array of rows:
public function layout(): array
{
return [\
Layout::accordion([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
]),\
];
}
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Icons | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/icons/# "Scroll to the top of the page")
Icons
=====
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/icons.md "View and edit this file on GitHub")
* [How to Use Icons](https://orchid.software/en/docs/icons/#how-to-use-icons)
* [Custom Icons](https://orchid.software/en/docs/icons/#custom-icons)
* [Using Blade Component](https://orchid.software/en/docs/icons/#using-blade-component)
* [Server-side Rendering with Templates](https://orchid.software/en/docs/icons/#server-side-rendering-with-templates)
The package comes with a set of icons that can be found on the [Bootstrap Icons](https://icons.getbootstrap.com/)
. These icons are prefixed with `bs.*` which is used as a prefix to identify the icons in your code.
> If you’re looking for a list of icons for previous versions, please visit the [Orchid Icon Pack page](https://orchid.software/en/docs/orchid-icons)
> .
[How to Use Icons](https://orchid.software/en/docs/icons/#how-to-use-icons)
----------------------------------------------------------------------------
You can easily add icons to elements like buttons, links, or menus in your application. Here’s a simple example to help you get started:
use Orchid\Screen\Actions\Menu;
Menu::make('Settings')
->icon('bs.gear') // Use the 'bs.' prefix for Bootstrap Icons
->route('platform.settings');
In this example, the icon `bs.gear` will show up next to the “Settings” link.
[Custom Icons](https://orchid.software/en/docs/icons/#custom-icons)
--------------------------------------------------------------------
In order to include an icon from a popular icon set such as Font Awesome, you can create a new directory for storing the icons. For example, you can create a new `icons` directory and a `fontawesome` subdirectory in your `resources` folder:
resources
- css
- icons
-- fontawesome
- js
- lang
- views
Once you have created the new directory, you can download the appropriate icons and place them in the new directory. For example, you can download the [notebook icon](https://github.com/FortAwesome/Font-Awesome/blob/ce084cb3463f15fd6b001eb70622d00a0e43c56c/svgs/solid/address-book.svg)
and place it in the `fontawesome` subdirectory.
Next, you need to configure the package to search for icons in the new directory. You can do this by editing the `config/platform.php` configuration file:
'icons' => [\
// other icon configurations\
'fa' => resource_path('icons/fontawesome')\
],
In the example above, we have declared the prefix “fa” and the directory where the icons are located.
In order to display the icons in the package’s components, you only need to pass the prefix and the icon’s name. For example, the icon definition in a menu would look like this:
Menu::make('Example of custom icons')
->icon('fa.address-book')
->url('https://orchid.software');
[Using Blade Component](https://orchid.software/en/docs/icons/#using-blade-component)
--------------------------------------------------------------------------------------
Icons can be easily integrated into your views using Blade components. Follow these steps to seamlessly incorporate icons in your views:
The code above renders the icon component with the specified icon path.
You can also apply additional attributes to your icon component:
You can also use the `Blade Icon Component` outside of the admin panel by [using the Blade component](https://github.com/orchidsoftware/blade-icons)
.
[Server-side Rendering with Templates](https://orchid.software/en/docs/icons/#server-side-rendering-with-templates)
--------------------------------------------------------------------------------------------------------------------
In our application, we rely solely on server-side rendering, which means we don’t specifically prepare icons for JavaScript control. However, it is still possible to use existing icons within JavaScript by utilizing the `` tag.
To illustrate this, you can include the following code on your page:
{name}
In the corresponding JavaScript code, you can use the template to create a DOM element with the desired content. Here’s an example:
let template = document.querySelector('#product-row');
let row = template.content.querySelector('tr').cloneNode(true);
row.innerHTML = row.innerHTML.replace(/{name}/gi, "Alexandr");
By substituting the `{name}` placeholder with the actual content, you can dynamically generate the desired element. You can then insert this element into your page wherever you need it.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Documentation | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/# "Scroll to the top of the page")
Documentation
=============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/index.md "View and edit this file on GitHub")
* [Introduction to Laravel Orchid](https://orchid.software/en/docs/#introduction-to-laravel-orchid)
* [Looking for Something Simpler?](https://orchid.software/en/docs/#looking-for-something-simpler)
* [Migrating to Orchid](https://orchid.software/en/docs/#migrating-to-orchid)
* [What Orchid Is Not](https://orchid.software/en/docs/#what-orchid-is-not)
* [What Sets Orchid Apart from Other Packages?](https://orchid.software/en/docs/#what-sets-orchid-apart-from-other-packages)
* [What Is Rapid Development?](https://orchid.software/en/docs/#what-is-rapid-development)
* [Is Something Wrong?](https://orchid.software/en/docs/#is-something-wrong)
[Introduction to Laravel Orchid](https://orchid.software/en/docs/#introduction-to-laravel-orchid)
--------------------------------------------------------------------------------------------------
**Laravel Orchid** is a powerful open-source package that simplifies the development and creation of administration-style applications. With its elegant and intuitive interface, developers can quickly implement beautiful and functional interfaces with minimal effort.
Some of the key features of Laravel Orchid include:
* A form builder that eliminates the need to manually describe HTML fields of the same type.
* Screens that provide a comfortable balance between CRUD generation and tedious coding.
* Over 40 different field types to choose from.
* Permissions management that makes it easy to manage user access in development and support.
* Additional features such as menus, charts, notifications, and more.
As a Laravel package, Orchid seamlessly integrates with other components and can serve as the foundation for applications such as content management systems.
> This documentation is intended for users familiar with the Laravel. If you are new to Laravel, it is recommended that you first read through the [framework documentation](https://laravel.com/docs/)
> before starting using Orchid.
[Looking for Something Simpler?](https://orchid.software/en/docs/#looking-for-something-simpler)
-------------------------------------------------------------------------------------------------
If you’re searching for a more straightforward solution for creating simple applications with minimal coding, Laravel Orchid’s **CRUD** feature may be a good fit for you. It offers a straightforward syntax that allows for easy creation of basic applications. To get started, take a look at the [CRUD section](https://orchid.software/en/docs/packages/crud/#introduction)
of the documentation.
[Migrating to Orchid](https://orchid.software/en/docs/#migrating-to-orchid)
----------------------------------------------------------------------------
If you currently have an admin panel based on `Blade` templates, you do not need to entirely rewrite your application in order to use package. Instead, you can gradually transition to using Orchid by [connecting old controllers](https://orchid.software/en/docs/controllers)
and integrating Orchid’s features into your existing application. This way, you can take advantage of Orchid’s powerful features without having to completely overhaul your existing codebase.
[What Orchid Is Not](https://orchid.software/en/docs/#what-orchid-is-not)
--------------------------------------------------------------------------
It’s crucial to understand that Orchid is a powerful tool for developers but not a “turnkey” solution. This means that it’s not suitable for individuals with little or no programming experience and demands a strong grasp of programming concepts to work comfortably with complex systems.
Furthermore, it’s important to recognize that not all developers may be open to using a new tool, and forcing it could lead to resistance or even sabotage. If you face resistance from your development team, it’s essential to have an open and honest conversation to address their concerns as best as possible. Seeking advice from an experienced professional could also be helpful in finding a mutually agreeable solution that works for everyone involved.
[What Sets Orchid Apart from Other Packages?](https://orchid.software/en/docs/#what-sets-orchid-apart-from-other-packages)
---------------------------------------------------------------------------------------------------------------------------
The Laravel ecosystem offers a variety of admin panels, such as Nova, Voyager, BackPack, and QuickAdminPanel, that aim to simplify the process of working with CRUD applications. However, Laravel Orchid stands out by offering a different approach to streamlining the development process.
Unlike other packages that rely on scaffolding or visual programming, Laravel Orchid is designed to be helpful at any stage of development and can grow with your application as it becomes more complex. Instead of generating physical stubs files or dragging and dropping objects, Orchid requires developers to write code using a keyboard. And instead of providing a single god class, it offers a range of small, reusable components that can be combined in various ways to build a wide range of applications.
Orchid’s approach is designed to be flexible, allowing developers to adapt it to their specific needs and workflows. It can be used for simple CRUD applications, but it also has the capability to handle more complex tasks.
[What Is Rapid Development?](https://orchid.software/en/docs/#what-is-rapid-development)
-----------------------------------------------------------------------------------------
A classic web application is a subsystem with a common three-tier architecture, which comprises:
* **Presentation level** – a graphical interface presented to the user (browser), including scripts, styles, and other resources.
* **The level of applied logic** – in our cases, this framework is the link where most business logic is concentrated, works with the database (Eloquent), sending resources, and various processing.
* **Level of resource management** – data storage using database management systems (MySQL, PostgreSQL, Microsoft SQL Server, SQLite).

It reduces development time, which is directly related to the distribution of responsibilities between levels. This is especially noticeable when it’s necessary to create auxiliary code. At the same time, most of the useful work is done by the application layer.
As various examples of conflicting tasks can be cited:
* Generation of “HTML” using the “Blade” template engine or the “Vue” framework.
* Use of ORM or stored procedures.
Depending on the choice of decisions, responsibilities are assigned, each decision having both advantages and disadvantages.
Similarly, the platform assigns new responsibilities to the application layer for managing the mapping and bridging of data.
Classic | Orchid
├── Route | ├── Route
├── Model | ├── Model
├── Controller | └── Screen
└── View |
├── HTML |
├── CSS |
└── JS |
[Is Something Wrong?](https://orchid.software/en/docs/#is-something-wrong)
---------------------------------------------------------------------------
If you find that something is missing or unclear in our documentation, we welcome contributions to improve it. You can click on the **Suggest Edits** link on the top right side of any documentation page to suggest changes.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Installation | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/installation/# "Scroll to the top of the page")
Installation
============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/installation.md "View and edit this file on GitHub")
* [Create a New Laravel Project](https://orchid.software/en/docs/installation/#create-a-new-laravel-project)
* [Add Dependency](https://orchid.software/en/docs/installation/#add-dependency)
* [Package Installation](https://orchid.software/en/docs/installation/#package-installation)
* [Create an Admin User](https://orchid.software/en/docs/installation/#create-an-admin-user)
* [Start the Development Server](https://orchid.software/en/docs/installation/#start-the-development-server)
* [Updating](https://orchid.software/en/docs/installation/#updating)
* [Keeping Assets Updated](https://orchid.software/en/docs/installation/#keeping-assets-updated)
* [What to Do Next?](https://orchid.software/en/docs/installation/#what-to-do-next)
Before you can use the Laravel Orchid, you need to install it. This guide should help you perform a simple installation to start the project.
[Create a New Laravel Project](https://orchid.software/en/docs/installation/#create-a-new-laravel-project)
-----------------------------------------------------------------------------------------------------------
> **Note.** If you already have Laravel installation, you can skip this step.
Being a package for the framework, you must first install Laravel. This can be done using the Composer dependency management tool by running the `composer create-project` command in your terminal:
composer create-project laravel/laravel orchid-project "12.*"
Or if you would prefer Laravel Installer:
composer global require laravel/installer
laravel new orchid-project
For more information on how to install Laravel, follow [Official Laravel Installation Guide](https://laravel.com/docs/installation)
.
> **Don’t you have Composer?** It’s easy to install by following the instructions on the [download page](https://getcomposer.org/download/)
> .
It will create a new `orchid-project` directory, load the dependencies, and generate the leading directories and files you need to get started. In other words, install your new framework project.
**Do not forget**
* Set “chmod -R o+w” rights to the `storage` and `bootstrap/cache` directories
* Edit the `.env` file
> **Note.** If you just installed Laravel, you may need to generate a key with command `php artisan key:generate`
[Add Dependency](https://orchid.software/en/docs/installation/#add-dependency)
-------------------------------------------------------------------------------
Go to the created project directory and run the command:
composer require orchid/platform
> **Note.** You also need to create a new database, update the `.env` file with credentials, and add your application’s URL to the variable `APP_URL`.
[Package Installation](https://orchid.software/en/docs/installation/#package-installation)
-------------------------------------------------------------------------------------------
> **Note:** During the installation process, the package will overwrite the `app/Models/User` model. However, it is important to note that replacing the model is not mandatory. You have the flexibility to customize the model according to your preferences. The package automatically applies certain configurations, such as `hidden` and `casts`, to the Eloquent model.
Run the installation process by running the command:
php artisan orchid:install
[Create an Admin User](https://orchid.software/en/docs/installation/#create-an-admin-user)
-------------------------------------------------------------------------------------------
To create a user with maximum permissions, you can run the following command with a username, email, and password:
php artisan orchid:admin
[Start the Development Server](https://orchid.software/en/docs/installation/#start-the-development-server)
-----------------------------------------------------------------------------------------------------------
If you haven’t installed a server (Nginx, Apache, etc.) to run the project, you can use the built-in server:
php artisan serve
Open a browser and go to `http://localhost:8000/admin`. If everything works, you will see the control panel login page. Later you can stop the server by pressing `Ctrl + C` in the terminal.
> **Note.** Suppose your runtime uses a different domain (e.g., orchid.loc). In that case, the admin panel may not be available. You need to specify your domain in the configuration file `config/platform.php` or `.env` file. It allows you to make the admin panel available on another domain or subdomain, such as `platform.example.com`.
[Updating](https://orchid.software/en/docs/installation/#updating)
-------------------------------------------------------------------
While in the project directory, use `Composer` to update the package:
composer update orchid/platform --with-dependencies
> **Note.** You can also update all your dependencies listed in the `composer.json` file by running `composer update`.
After updating to a new release, you should be sure to update JavaScript and CSS assets using `orchid:publish` and clear any cached views with `view:clear`. It will ensure the newly-updated version is using the latest versions.
php artisan orchid:publish
php artisan view:clear
[Keeping Assets Updated](https://orchid.software/en/docs/installation/#keeping-assets-updated)
-----------------------------------------------------------------------------------------------
To make sure that your assets are promptly updated whenever a new version is downloaded, you can easily add a Composer hook to your project’s `composer.json` file. This will automatically publish the latest assets for you:
{
"scripts": {
"post-update-cmd": [\
"@php artisan orchid:publish --ansi"\
]
}
}
Once you have added this hook, you can rest assured that your assets will always be up-to-date and functioning properly. And if you ever want to verify that the assets are indeed current, you can simply use the `artisan` console command to check:
php artisan about
This command will provide you with an importance of information, including some of the details about the package itself. It’s ensuring that your environment is correctly configured and running as expected.
> **Problems encountered during installation?** It is possible that someone already had this problem [https://github.com/orchidsoftware/platform/issues](https://github.com/orchidsoftware/platform/issues)
> . If not, you can send a message or ask for [help](https://github.com/orchidsoftware/platform/issues/new)
> .
[What to Do Next?](https://orchid.software/en/docs/installation/#what-to-do-next)
----------------------------------------------------------------------------------
A newly installed package already has several screens that show various input fields, masks, states, as well as some interface layout. You can try them out or go directly to the step by step examples of working with the package on the [“Quick Start” page](https://orchid.software/en/docs/quickstart)
or read the [documentation](https://orchid.software/en/docs/screens)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Legend | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/legend/# "Scroll to the top of the page")
Legend
======
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/legend.md "View and edit this file on GitHub")
The Legend layout is used to display a single model or array of data in a clear and concise way. The layout supports short, concise syntax for defining the data to be displayed, as well as the ability to customize the rendering of individual data points using closures or Blade components.
Here is an example of how to use the Legend layout:
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Sight;
/**
* Fetch data to be displayed on the screen.
*/
public function query(): iterable
{
return [\
'user' => Auth::user(),\
];
}
/**
* The screen's layout elements.
*/
public function layout(): array
{
return [\
Layout::legend('user', [\
Sight::make('id'),\
Sight::make('name'),\
Sight::make('email'),\
]),\
];
}
In the example above, the first argument passed to the `Layout::legend()` method is the key for the data to be displayed. This key should correspond to an array or model that has been passed to the screen’s `query` method. The second argument is an array of `Sight` objects, each representing a data point to be displayed.

Many methods of the `Sight` class are similar to those of the `TD` class used in the [Table](https://orchid.software/en/docs/table)
layout. For example, you can add a popover to provide additional information about a data point:
Layout::legend('user', [\
Sight::make('id')->popover('Unique number in the system'),\
]),
If you need to perform additional processing or rendering for a particular data point, you can use the `render` method and pass in a closure function:
Layout::legend('user', [\
Sight::make('id')->render(fn() => 'Any html'),\
]),
If you need to perform similar processing for multiple data points, a more appropriate solution would be to create a Blade component and specify it using the `component` method:
Layout::legend('user', [\
Sight::make('id')->component(IdInformation::class),\
]),
Blade components work in a similar way to those used in the [Table](https://orchid.software/en/docs/table)
layout. You can find more examples and information about using Blade components [here](https://laravel.com/docs/blade#components)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Use JavaScript | Orchid - Laravel Admin Panel
 
[](https://orchid.software/en/docs/javascript/# "Scroll to the top of the page")
Use JavaScript
==============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/en/docs/javascript.md "View and edit this file on GitHub")
* [Working With Vite](https://orchid.software/en/docs/javascript/#working-with-vite)
* [Loading Your Scripts And Styles](https://orchid.software/en/docs/javascript/#loading-your-scripts-and-styles)
* [Turbo](https://orchid.software/en/docs/javascript/#turbo)
* [Stimulus](https://orchid.software/en/docs/javascript/#stimulus)
* [Compilation with Mix](https://orchid.software/en/docs/javascript/#compilation-with-mix)
* [Compilation with Vite](https://orchid.software/en/docs/javascript/#compilation-with-vite)
* [Run Controller](https://orchid.software/en/docs/javascript/#run-controller)
* [Vue.js Wrapped in a Stimulus](https://orchid.software/en/docs/javascript/#vuejs-wrapped-in-a-stimulus)
The aesthetic and functional foundation of Orchid is built upon [Bootstrap](http://getbootstrap.com/)
for CSS and [Hotwired](https://hotwired.dev/)
for JavaScript functionality. While Orchid allows the integration of additional libraries to meet your project’s needs, we recommend utilizing these core technologies to leverage the full potential of Orchid’s features.
> **Note**: Orchid includes a raw Bootstrap stylesheet, which means you have the full spectrum of Bootstrap’s styles at your disposal.
[Working With Vite](https://orchid.software/en/docs/javascript/#working-with-vite)
-----------------------------------------------------------------------------------
Laravel comes with the powerful front-end build tool called Vite by default. To harness the full potential of this tool, make sure Vite is installed and configured correctly. You can find installation and configuration instructions in the official [documentation page](https://laravel.com/docs/vite)
.
To successfully incorporate the acquired resources into your project, you’ll need to specify them in the `config/platform.php` file. This file allows you to define a list of resources that should be included in your project. Here’s an example of such configuration:
'vite' => [\
'resources/js/app.js',\
],
This entry is equivalent to using the Blade directive `@vite`. By carefully following these steps, you can effectively integrate Vite into your Laravel project and achieve the best results from its usage.
[Loading Your Scripts And Styles](https://orchid.software/en/docs/javascript/#loading-your-scripts-and-styles)
---------------------------------------------------------------------------------------------------------------
Laravel Orchid facilitates efficient delivery of your stylesheets and scripts by allowing the use of any `` or `
Внутри блока `script` создается и сразу же регистрируется в приложении, без необходимости создания отдельного файла, [Stimulus](https://stimulus.hotwired.dev/handbook/introduction)
\-контроллер, он подключается к `html` с помощью аттрибута `data-controller`. Вы можете использовать все возможности Stimulus для создания своего поля.
[Основы использования Stimulus](https://orchid.software/ru/docs/custom-field/#osnovy-ispolzovaniia-stimulus)
-------------------------------------------------------------------------------------------------------------
Orchid использует Stimulus для добавления интерактивности элементам интерфейса. Этот легковесный фреймворк позволяет связывать JavaScript-логику с HTML через data-атрибуты, что особенно удобно при создании динамических полей.
### [Структура контролеера](https://orchid.software/ru/docs/custom-field/#struktura-kontroleera)
Рассмотрим пример контроллера из шаблона EmojiPicker:
* Имя контроллера: `emoji-picker` (указывается в `data-controller`).
* **Targets**: Элементы DOM, к которым нужен доступ (ищутся по `data--target`).
* Жизненный цикл:
* `connect()` – вызывается при подключении контроллера к элементу.
* `disconnect()` – вызывается при удалении элемента из DOM.
* **Методы**: Произвольные функции для обработки событий (например, `greet()`).
### [Связь c HMTL](https://orchid.software/ru/docs/custom-field/#sviaz-c-hmtl)
* **Контроллер:** `data-controller="emoji-picker"` инициализирует контроллер на элементе.
* **Targets:**
* `data-emoji-picker-target="name"` → доступ через `this.nameTarget`
* `data-emoji-picker-target="output"` → `this.outputTarget`
* **Действия:**
* `data-action="input->emoji-picker#greet"` – при событии input вызывать метод greet контроллера.
### [Регистрация контроллера](https://orchid.software/ru/docs/custom-field/#registraciia-kontrollera)
Метод Orchid.register() регистрирует контроллер в приложении:
Orchid.register('controller-name', class extends Controller {
// Логика контроллера
});
### [Работа с элементами](https://orchid.software/ru/docs/custom-field/#rabota-s-elementami)
* **Одиночный элемент**: `this.Target` (например, this.nameTarget)
* **Все элементы:** `this.Targets` (массив элементов)
* **Query-селекторы:**
* `this.element` – главный элемент контроллера
* `this.findElement(selector)` – поиск внутри элемента
### [Интеграция сторонних библиотек](https://orchid.software/ru/docs/custom-field/#integraciia-storonnix-bibliotek)
> Возможно потребуется компиляция, через Vite, в таком случае посмотрите раздел об использовании [JavaScript](https://orchid.software/ru/docs/javascript/)
Рассмотрим на примере DatePicker:
Orchid.register('date-picker', class extends Controller {
connect() {
new DatePicker(this.element, {
format: 'YYYY-MM-DD'
});
}
});
[Stimulus](https://stimulus.hotwired.dev/handbook/introduction)
позволяет органично интегрировать любые JavaScript-библиотеки, сохраняя код модульным и легко поддерживаемым.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Универсальные макеты | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/custom-template/# "Scroll to the top of the page")
Универсальные макеты
====================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/custom-template.md "View and edit this file on GitHub")
* [Пользовательский шаблон](https://orchid.software/ru/docs/custom-template/#polzovatelskii-sablon)
* [Обертка](https://orchid.software/ru/docs/custom-template/#obertka)
* [Компоненты](https://orchid.software/ru/docs/custom-template/#komponenty)
* [Browsing](https://orchid.software/ru/docs/custom-template/#browsing)
* [Расширение](https://orchid.software/ru/docs/custom-template/#rassirenie)
[Пользовательский шаблон](https://orchid.software/ru/docs/custom-template/#polzovatelskii-sablon)
--------------------------------------------------------------------------------------------------
Вполне ожидаемая ситуация, когда необходимо отобразить собственный `blade` шаблон. Для этого необходимо вызвать `Layout::view`, передав параметром строку имени:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::view('myTemplate'),\
];
}
Все данные из метода `query` будут переданы в Ваш шаблон.
// ... Screen
public function query(): array
{
return [\
'name' => 'Alexandr Chernyaev',\
];
}
public function layout(): array
{
return [\
Layout::view('hello'),\
];
}
Вы можете отобразить содержимое `name` вот так:
// ... /views/hello.blade.php
Hello {{ $name }}!
[Обертка](https://orchid.software/ru/docs/custom-template/#obertka)
--------------------------------------------------------------------
Промежуточным звеном между “Пользовательским шаблоном” и стандартными слоями может служить “Обёртка”, которая позволяет указывать, где именно должны отображаться другие слои.
public function layout(): array
{
return [\
Layout::wrapper('myTemplate', [\
'foo' => [\
RowLayout::class,\
RowLayout::class,\
],\
'bar' => RowLayout::class,\
]),\
];
}
В шаблон `myTemplate` будут переданы переменные `foo` и `bar`, содержащие уже собранные `View`, которые можно выводить:
@foreach($foo as $row)
{!! $row !!}
@endforeach
{!! $bar !!}
Переменные из `query` так же доступны в шаблоне.
[Компоненты](https://orchid.software/ru/docs/custom-template/#komponenty)
--------------------------------------------------------------------------
Одним из способов повторного использования шаблонов является создание `Blade` компонентов. Такие компоненты могут быть использованы и в платформе.
Для того чтобы создать новый компонент, воспользуемся `artisan` командой:
php artisan make:component Hello --inline
> **Примечание.** Более подробно Вы можете узнать о компонентах в [документации фреймворка](https://laravel.com/docs/blade#components)
В результате будет новый класс `Hello`, приведём его в следующий вид:
namespace App\View\Components;
use Illuminate\View\Component;
class Hello extends Component
{
/**
* @var string
*/
public $name;
/**
* Create a new component instance.
*
* @param string $name
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return <<<'blade'
Hello {{ $name }}!
blade;
}
}
Для использования этого класса в экранах необходимо передать его строчное представление:
/**
* Query data.
*
* @return array
*/
public function query(): array
{
return [\
'name' => 'Sheldon Cooper',\
];
}
/**
* Views.
*
* @return Layout[]
*/
public function layout(): array
{
return [\
Layout::component(Hello::class),\
];
}
Значения из `query` будут подставлены в компонент по имени. При этом отсутствующие значения могут быть добавлены из контейнера, например:
namespace App\View\Components;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\View\Component;
class Hello extends Component
{
/**
* @var string
*/
public $name;
/**
* @var Application
*/
public $application;
/**
* Create a new component instance.
*
* @param Application $application
* @param string $name
*/
public function __construct(Application $application, string $name)
{
$this->application = $application;
$this->name = $name;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return <<<'blade'
Hello {{ $name }}!
Version {{ $application->version() }}
blade;
}
}
[Browsing](https://orchid.software/ru/docs/custom-template/#browsing)
----------------------------------------------------------------------
Панель администратора — это место, где вы можете просматривать и выполнять все необходимые действия в проекте. Но иногда технология и графический вид не соответствуют друг другу и расположены по разным адресам (Например, если вы используете [Telescope](https://laravel.com/docs/telescope)
или [Horizon](https://laravel.com/docs/horizon)
). Это приводит к тому, что вам нужно постоянно перемещаться между двумя вкладками браузера.
Чтобы избежать этого, вы можете открыть iframe для просмотра другой страницы:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::browsing('http://127.0.0.1:8000/telescope'),\
];
}
Attributes are also available to the html definition:
Layout::browsing('http://127.0.0.1:8000/telescope')
->allow('...')
->loading('...')
->csp('...')
->name('...')
->referrerpolicy('...')
->sandbox('...')
->src('...')
->srcdoc('...');
[Расширение](https://orchid.software/ru/docs/custom-template/#rassirenie)
--------------------------------------------------------------------------
Класс `Layouts` является группирующим нескольких различных. Для того чтобы добавить в него новую возможность, достаточно указать её в сервис провайдере как:
use Orchid\Screen\Layout;
use Orchid\Screen\LayoutFactory;
use Orchid\Screen\Repository;
LayoutFactory::macro('hello', function (string $name) {
return new class($name) extends Layout
{
/**
* @ string
*/
public $name;
/**
* Hello constructor.
*
* @param string $name
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* @param Repository $repository
*
* @return mixed
*/
public function build(Repository $repository)
{
return view('hello')->with('name', $this->name);
}
};
});
Тогда в экране вызов будет выглядеть как:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::hello('Alexandr Chernyaev')\
];
}
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Фильтры | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/filters/# "Scroll to the top of the page")
Фильтры
=======
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/filters.md "View and edit this file on GitHub")
* [Классический фильтр](https://orchid.software/ru/docs/filters/#klassiceskii-filtr)
* [Selection](https://orchid.software/ru/docs/filters/#selection)
* [Автоматическая HTTP фильтрация и сортировка](https://orchid.software/ru/docs/filters/#avtomaticeskaia-http-filtraciia-i-sortirovka)
Фильтры служат для упрощения поиска записей с использованием типичного фильтра. Например, если вы хотите отфильтровать каталог продуктов по атрибутам, брендам и т.п. Выборка значений основана на параметрах Http запросов.
> Это не является готовым решением или универсальным средством, вы должны расширить структуру для своих конкретных приложений.
[Классический фильтр](https://orchid.software/ru/docs/filters/#klassiceskii-filtr)
-----------------------------------------------------------------------------------
Для создания сложных запросов, вы можете использовать фильтры Eloquent, которые позволяют вам полностью управлять собой. Существует команда для создания нового фильтра:
php artisan orchid:filter QueryFilter
Это создаст класс фильтра в папке `app/Http/Filters`. Пример фильтра:
namespace App\Http\Filters;
use Orchid\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class QueryFilter extends Filter
{
/**
* @var array
*/
public $parameters = ['query'];
/**
* @param Builder $builder
*
* @return Builder
*/
public function run(Builder $builder): Builder
{
return $builder->where('demo', $this->request->get('query'));
}
/**
* @return Field[]
*/
public function display() : array
{
return [\
Input::make('email')\
->type('text')\
->value($this->request->get('email'))\
->placeholder('Search...')\
->title('Search')\
];
}
}
Фильтр сработает при наличии хотя бы одного параметра, указанного в массиве `$parameters`. Если массив будет пуст, то фильтр будет работать при каждом запросе.
> **Примечание.** Вы можете использовать одни и те же фильтры для разных моделей.
Для использования фильтров требуется подключить трейт `Orchid\Filter\Filterable` в вашу модель и передавать в функцию `filters` массив классов:
use App\Model;
Model::filters([Filter::class])->simplePaginate();
[Selection](https://orchid.software/ru/docs/filters/#selection)
----------------------------------------------------------------
Когда вам нужно отобразить фильтры и применить их к модели, их удобнее сгруппировать, создав отдельный слой «Selection». Для создания нового слоя выполните команду:
php artisan orchid:selection MySelection
В этом классе есть один-единственный метод, в котором необходимо перечислить все фильтры, которые должны отображаться и применяться, например:
namespace App\Orchid\Layouts;
use Orchid\Platform\Filters\Filter;
use Orchid\Press\Http\Filters\CreatedFilter;
use Orchid\Press\Http\Filters\SearchFilter;
use Orchid\Screen\Layouts\Selection;
class MySelection extends Selection
{
/**
* @return Filter[]
*/
public function filters(): array
{
return [\
SearchFilter::class,\
CreatedFilter::class\
];
}
}
После этого мы можем применить его к модели:
Model::filters(MySelection::class)->simplePaginate();
Поскольку это слой, его также можно использовать для отображения полей на экране:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
MySelection::class,\
];
}
[Автоматическая HTTP фильтрация и сортировка](https://orchid.software/ru/docs/filters/#avtomaticeskaia-http-filtraciia-i-sortirovka)
-------------------------------------------------------------------------------------------------------------------------------------
Для реагирования на HTTP параметры, модель должна включать в себя `Filterable`, а так же определение доступных атрибутов:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Orchid\Filters\Filterable;
use Orchid\Filters\Types\Like;
use Orchid\Filters\Types\Where;
use Orchid\Filters\Types\WhereDate;
use Orchid\Filters\Types\WhereMaxMin;
use Orchid\Filters\Types\WhereDateStartEnd;
class Post extends Model
{
use Filterable;
/**
* @var array
*/
protected $allowedFilters = [\
'id' => Where::class,\
'user_id' => WhereIn::class,\
'rating' => WhereMaxMin::class,\
'content' => Like::class,\
'publish_at' => WhereDate::class,\
'created_at' => WhereDateStartEnd::class,\
'deleted_at' => WhereDateStartEnd::class,\
];
/**
* @var array
*/
protected $allowedSorts = [\
'id',\
'user_id',\
'rating',\
'publish_at',\
'created_at',\
'deleted_at',\
];
}
Использование заключается в вызове метода `filters`:
Post::filters()->defaultSort('id')->paginate();
> **Примечание.** Автоматические HTTP фильтры не будут работать с отношениями. Если вас это интересует, вы можете использовать классический фильтр, описанный выше.
Как будет реагировать сортировка на HTTP параметры:
http://example.com/demo?sort=content
$model->orderBy('content', 'asc');
http://example.com/demo?sort=-content
$model->orderBy('content', 'desc');
Отличным способом будет использовать такую сортировку в таблицах. Для того чтобы заголовки колонки стали активными, используйте:
use Orchid\Screen\TD;
TD::make('name')->sort();
Автоматическая сортировка и фильтрация HTTP запросов не будут работать с полями моделей, полученными через связи. Если вам необходима сортировка или фильтрация по таким полям, вы можете воспользоваться сторонними пакетами, например [Eloquent Power Joins](https://github.com/kirschbaum-development/eloquent-power-joins)
. С его помощью можно решить эту проблему:
User::orderByPowerJoins('profile.city');
User::orderByPowerJoins('profile.city', 'desc');
Однако вам потребуется самостоятельно написать обработчик для HTTP-параметров sort и filter, так как пакет не автоматически распознает, что знак `-` перед названием поля означает порядок сортировки “desc”, а также каким образом применять фильтры. Вы можете сделать это используя “Фильтр”. Кроме того, следует использовать методы пакета только в случае сортировки или фильтрации по полям, доступным через связи.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Глобальный поиск | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/global-search/# "Scroll to the top of the page")
Глобальный поиск
================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/global-search.md "View and edit this file on GitHub")
* [Использование полнотекстового поиска](https://orchid.software/ru/docs/global-search/#ispolzovanie-polnotekstovogo-poiska)
* [Модификация результатов](https://orchid.software/ru/docs/global-search/#modifikaciia-rezultatov)
[Использование полнотекстового поиска](https://orchid.software/ru/docs/global-search/#ispolzovanie-polnotekstovogo-poiska)
---------------------------------------------------------------------------------------------------------------------------
Платформа поставляется с пакетом [Laravel Scout](https://github.com/laravel/scout)
, который является абстракцией для полнотекстового поиска в ваши модели `Eloquent`. Так как **`Scout` не содержит самого «драйвера» поиска**, требуется поставить и указать требуемое решение, это могут быть elasticsearch, algolia, sphinx или другие решения.
> В этом примере используется [представители](https://orchid.software/ru/docs/presenters)
> , настоятельно рекомендуется ознакомится с ними. А так же произвести действия по настройки модели из документации [Laravel Scout](https://github.com/laravel/scout)
> .
Для того чтобы приложение имело информацию о том, какие модели должны участвовать в поиске, необходимо зарегистрировать их в сервис провайдере:
namespace App\Providers;
use App\Idea;
use Orchid\Platform\Dashboard;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Boot the application events.
*
* @param Dashboard $dashboard
*/
public function boot(Dashboard $dashboard)
{
$dashboard->registerSearch([\
Idea::class,\
//...Models\
]);
}
}
Отображение результатов осуществляется с помощью вызова `presenter()` у объекта.
namespace App;
use App\Orchid\Presenters\IdeaPresenter;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Idea extends Model
{
use Searchable;
/**
* Get the presenter for the model.
*
* @return IdeaPresenter
*/
public function presenter()
{
return new IdeaPresenter($this);
}
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
$array = $this->toArray();
// Customize array...
return $array;
}
}
В представителе укажем интерфейс `Searchable` и определим методы, которые будут возвращать значения для показа пользователю, например так:
namespace App\Orchid\Presenters;
use Laravel\Scout\Builder;
use Orchid\Screen\Contracts\Searchable;
use Orchid\Support\Presenter;
class IdeaPresenter extends Presenter implements Searchable
{
/**
* @return string
*/
public function label(): string
{
return 'Ideas';
}
/**
* @return string
*/
public function title(): string
{
return $this->entity->name;
}
/**
* @return string
*/
public function subTitle(): string
{
return 'Small descriptions';
}
/**
* @return string
*/
public function url(): string
{
return url('/');
}
/**
* @return string
*/
public function image(): ?string
{
return null;
}
/**
* @param string|null $query
*
* @return Builder
*/
public function searchQuery(string $query = null): Builder
{
return $this->entity->search($query);
}
/**
* @return int
*/
public function perSearchShow(): int
{
return 3;
}
}
[Модификация результатов](https://orchid.software/ru/docs/global-search/#modifikaciia-rezultatov)
--------------------------------------------------------------------------------------------------
Для модификации запросов, например, чтобы выдавать в результатах только актуальные данные, можно модифицировать запрос с помощью переопределения метода:
public function searchQuery(string $query = null): Builder
{
return $this->entity->search($query)->where('active', true);
}
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Элементы формы | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/field/# "Scroll to the top of the page")
Элементы формы
==============
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/field.md "View and edit this file on GitHub")
* [Input](https://orchid.software/ru/docs/field/#input)
* [Пользовательское оформление](https://orchid.software/ru/docs/field/#polzovatelskoe-oformlenie)
* [Обязательное для заполнения](https://orchid.software/ru/docs/field/#obiazatelnoe-dlia-zapolneniia)
* [Скрытие полей](https://orchid.software/ru/docs/field/#skrytie-polei)
* [Типы](https://orchid.software/ru/docs/field/#tipy)
* [Маска для ввода значений](https://orchid.software/ru/docs/field/#maska-dlia-vvoda-znacenii)
* [TextArea](https://orchid.software/ru/docs/field/#textarea)
* [CheckBox](https://orchid.software/ru/docs/field/#checkbox)
* [Select](https://orchid.software/ru/docs/field/#select)
* [Relation](https://orchid.software/ru/docs/field/#relation)
* [DateTime](https://orchid.software/ru/docs/field/#datetime)
* [DateRange](https://orchid.software/ru/docs/field/#daterange)
* [TimeZone](https://orchid.software/ru/docs/field/#timezone)
* [HTML редактор Quill](https://orchid.software/ru/docs/field/#html-redaktor-quill)
* [Markdown редактор](https://orchid.software/ru/docs/field/#markdown-redaktor)
* [Matrix](https://orchid.software/ru/docs/field/#matrix)
* [Редактор кода](https://orchid.software/ru/docs/field/#redaktor-koda)
* [Cropper](https://orchid.software/ru/docs/field/#cropper)
* [Ширина и высота](https://orchid.software/ru/docs/field/#sirina-i-vysota)
* [Ограничение размера файла](https://orchid.software/ru/docs/field/#ogranicenie-razmera-faila)
* [Значение](https://orchid.software/ru/docs/field/#znacenie)
* [Attach](https://orchid.software/ru/docs/field/#attach)
* [Ограничение загружаемых файлов](https://orchid.software/ru/docs/field/#ogranicenie-zagruzaemyx-failov)
* [Группировка файлов](https://orchid.software/ru/docs/field/#gruppirovka-failov)
* [Работа с хранилищами файлов](https://orchid.software/ru/docs/field/#rabota-s-xranilishhami-failov)
* [Явная настройка пути к файлам](https://orchid.software/ru/docs/field/#iavnaia-nastroika-puti-k-failam)
* [Валидация и сортировка файлов на сервере](https://orchid.software/ru/docs/field/#validaciia-i-sortirovka-failov-na-servere)
* [Обработка ошибок и вывод сообщений](https://orchid.software/ru/docs/field/#obrabotka-osibok-i-vyvod-soobshhenii)
* [Group](https://orchid.software/ru/docs/field/#group)
* [Ширина колонок](https://orchid.software/ru/docs/field/#sirina-kolonok)
* [Выравнивание колонок](https://orchid.software/ru/docs/field/#vyravnivanie-kolonok)
* [Кнопка](https://orchid.software/ru/docs/field/#knopka)
* [Подтверждение действия](https://orchid.software/ru/docs/field/#podtverzdenie-deistviia)
* [Указание URL для отправки данных](https://orchid.software/ru/docs/field/#ukazanie-url-dlia-otpravki-dannyx)
* [Скачивание файла](https://orchid.software/ru/docs/field/#skacivanie-faila)
* [Ссылка](https://orchid.software/ru/docs/field/#ssylka)
* [Открытие ссылки в новой вкладке](https://orchid.software/ru/docs/field/#otkrytie-ssylki-v-novoi-vkladke)
* [Скачивание файла](https://orchid.software/ru/docs/field/#skacivanie-faila)
* [Выпадающее меню (Dropdown)](https://orchid.software/ru/docs/field/#vypadaiushhee-meniu-dropdown)
* [NumberRange](https://orchid.software/ru/docs/field/#numberrange)
Поля используются для генерации вывода шаблона формы заполнения и редактирования.
> Не стесняйтесь добавлять свои поля, например, для использования удобного редактора для вас или любых компонентов. Документация по созданию ногового поля находится в разделе [Пользовательские поля.](https://orchid.software/ru/docs/custom-field)
> .
[Input](https://orchid.software/ru/docs/field/#input)
------------------------------------------------------
Является одним из разносторонних элементов формы и позволяет создавать разные части интерфейса и обеспечивать взаимодействие с пользователем. Главным образом предназначен для создания текстовых полей.

Пример записи:
use Orchid\Screen\Fields\Input;
Input::make('name');
### [Пользовательское оформление](https://orchid.software/ru/docs/field/#polzovatelskoe-oformlenie)
Пустые и невыразительные поля для ввода могут запутывать пользователя, но вы можете помочь, указав заголовок.
Input::make('name')
->title('First name');
Когда требуется более подробно описать предназначение поля, тогда можно использовать подсказку:
Input::make('name')
->help('What is your name?');
Если описание поля очень специфическое и требуется большое описание, можно использовать тултип, который будет показан в качестве всплывающего окна:
Input::make('name')
->popover('Tooltip - hint that user opens himself.');
Горизонтальное или вертикальное представление:
Input::make('name')->vertical();
Input::make('name')->horizontal();
### [Обязательное для заполнения](https://orchid.software/ru/docs/field/#obiazatelnoe-dlia-zapolneniia)
Иногда вам может потребоваться указать поле обязательным к заполнению, для этого необходимо вызвать метод `required`:
Input::make('name')
->type('text')
->required();
### [Скрытие полей](https://orchid.software/ru/docs/field/#skrytie-polei)
Иногда необходимо временно или на постоянной основе скрыть поле из пользовательского интерфейса. Для того чтобы скрыть элемент формы, необходимо использовать метод `canSee` и передать в него значение `false`:
Input::make('name')->canSee(false);
Если же Вы хотите отобразить скрытый элемент снова, то нужно использовать метод `canSee` и передать в него значение `true`:
Input::make('name')->canSee(true);
> Заметьте, многие методы, такие как `canSee`, `required`, `title`, `help`, `vertical`, `horizontal` и многие другие, доступны почти в каждом `поле` системы.
### [Типы](https://orchid.software/ru/docs/field/#tipy)
Input – одно из самых универсальных полей за счет указания типа, поддерживаются все `html` значения:
> **Обратите внимание**. Поддержка новых HTML5 атрибутов полностью зависит от используемого браузера.
Текстовое поле. Предназначено для ввода символов с помощью клавиатуры.
Input::make('name')->type('text');
Поле для ввода имени файла, который пересылается на сервер.
Input::make('name')->type('file');
Скрытое поле.
Input::make('name')->type('hidden');
Виджет для выбора цвета.
Input::make('name')->type('color');
Для адресов электронной почты.
Input::make('name')->type('email');
Ввод чисел.
Input::make('name')->type('number');
Ползунок для выбора чисел в указанном диапазоне.
Input::make('name')->type('range');
Для указания веб-адресов.
Input::make('name')->type('url');
Более подробно о атрибуте `type` можно узнать на [сайте Mozilla](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input)
.
### [Маска для ввода значений](https://orchid.software/ru/docs/field/#maska-dlia-vvoda-znacenii)
Отлично подходит если значения должны быть записаны в стандартном виде, например ИНН или номер телефона
Пример записи:
Input::make('phone')
->mask('(999) 999-9999')
->title('Номер телефона');
В маску можно передавать массив с параметрами, например:
Input::make('price')
->title('Стоимость')
->mask([\
'mask' => '999 999 999.99',\
'numericInput' => true\
]);
Input::make('price')
->title('Стоимость')
->mask([\
'alias' => 'currency',\
'prefix' => ' ',\
'groupSeparator' => ' ',\
'digitsOptional' => true,\
]);
Все доступные параметры _Inputmask_ можно посмотреть [здесь](https://github.com/RobinHerbots/Inputmask#options)
.
[TextArea](https://orchid.software/ru/docs/field/#textarea)
------------------------------------------------------------
Поле `textarea` представляет собой элемент формы для создания области, в которую можно вводить несколько строк текста. В отличие от тега `input` в текстовом поле допустимо делать переносы строк, они сохраняются при отправке данных на сервер.
Пример записи:
TextArea::make('description');
Вы можете задать необходимое количество строк с помощью метода `rows`:
TextArea::make('description')
->rows(5);
[CheckBox](https://orchid.software/ru/docs/field/#checkbox)
------------------------------------------------------------
Элемент графического пользовательского интерфейса, позволяющий пользователю управлять параметром с двумя состояниями — ☑ включено и ☐ выключено.
Пример записи:
CheckBox::make('free')
->value(1)
->title('Free')
->placeholder('Event for free')
->help('Event for free');
По умолчанию браузеры не отправляют значения невыбранного поля. Это осложняет установку простых булевых типов. Для решения этого есть отдельный метод, при использовании которого значение `false` будет отправлено:
CheckBox::make('enabled')
->sendTrueOrFalse();
[Select](https://orchid.software/ru/docs/field/#select)
--------------------------------------------------------
Простой выбор из списка массива:
Select::make('select')
->options([\
'index' => 'Index',\
'noindex' => 'No index',\
])
->title('Select tags')
->help('Allow search bots to index');
Работа с источником:
Select::make('user')
->fromModel(User::class, 'email');
Источник с условием:
Select::make('user')
->fromQuery(User::where('balance', '!=', '0'), 'email');
Изменение ключа:
Select::make('user')
->fromModel(User::class, 'email', 'uuid');
Возможны ситуации, когда необходимо добавить некоторое значение, которое означает, что поле не выбрано. Для этого можно использовать метод `empty`:
// Для массива
Select::make('user')
->options([\
1 => 'Пункт 1',\
2 => 'Пункт 2',\
])
->empty('Не выбрано');
// Для источника
Select::make('user')
->fromModel(User::class, 'name')
->empty('Не выбрано');
> **Обратите внимание**, что `empty` вызывается позднее заполняющих методов, иначе добавленное значение будет перезаписано.
Метод `empty` так же принимает и второй аргумент, отвечающий за значение:
Select::make('user')
->empty('Не выбрано', 0)
->options([\
1 => 'Пункт 1',\
2 => 'Пункт 2',\
]);
[Relation](https://orchid.software/ru/docs/field/#relation)
------------------------------------------------------------
Поля отношения могут подгружать динамические данные, это хорошее решение, если вам нужны связи.
Relation::make('idea')
->fromModel(Idea::class, 'name')
->title('Выберите свою идею');
Для множественного выбора примените метод `multiple()`
Relation::make('ideas.')
->fromModel(Idea::class, 'name')
->multiple()
->title('Выберите свои идеи');
> **Примечание.** Обратите внимание на точку в конце имени. Она необходима для того, чтобы показать ожидаемость массива. Как если бы это был `HTML` код ``
Для модификации загрузки можно использовать указание на `scope` модели, например, взять только активные:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Idea extends Model
{
/**
* @param Builder $query
*
* @return Builder
*/
public function scopeActive(Builder $query)
{
return $query->where('active', true);
}
}
Relation::make('idea')
->fromModel(Idea::class, 'name')
->applyScope('active')
->title('Выберите свою идею');
Вы также можете передавать в метод дополнительные параметры:
Relation::make('idea')
->fromModel(Idea::class, 'name')
->applyScope('status', 'active')
->title('Выберите свою идею');
Вы можете добавить одно или несколько полей, по которым будет дополнительно осуществляться поиск:
Relation::make('idea')
->fromModel(Idea::class, 'name')
->searchColumns('author', 'description')
->title('Choose your idea');
Чтобы установить количество элементов, которые будут перечислены в результате поиска, Вы можете использовать метод chunk, передав количество результатов поиска в качестве параметра:
Relation::make('users.')
->fromModel(User::class, 'name')
->chunk(20);
Опции выбора могут работать с вычисляемыми полями, но только для отображения результата, поиск будет происходить только по одной колонке в базе данных. Для этого используется метод `displayAppend`.
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getFullAttribute(): string
{
return sprintf('%s (%s)', $this->name, $this->email);
}
}
Для указания отображаемого поля необходимо:
Relation::make('users.')
->fromModel(User::class, 'name')
->displayAppend('full')
->multiple()
->title('Select users');
[DateTime](https://orchid.software/ru/docs/field/#datetime)
------------------------------------------------------------
Позволяет выбрать дату и время.

Пример записи:
DateTimer::make('open')
->title('Opening date');
Разрешить прямой ввод:
DateTimer::make('open')
->title('Opening date')
->allowInput();
**Обратите внимание**, что установка поля обязательным может быть только при условии прямого ввода:
DateTimer::make('open')
->title('Opening date')
->allowInput()
->required();
Формат данных:
DateTimer::make('open')
->title('Opening date')
->format('Y-m-d');
Пример, для отображения в 24-ом формате:
DateTimer::make('open')
->title('Opening date')
->format24hr();
Календарь со временем:
DateTimer::make('open')
->title('Opening time')
->enableTime();
Выбор только времени:
DateTimer::make('open')
->title('Opening time')
->noCalendar()
->format('h:i K');
[DateRange](https://orchid.software/ru/docs/field/#daterange)
--------------------------------------------------------------
Позволяет выбрать диапазон даты (и времени).
Пример:
DateRange::make('open')
->title('Opening between');
[TimeZone](https://orchid.software/ru/docs/field/#timezone)
------------------------------------------------------------
Поле для удобного выбора часового пояса:
TimeZone::make('time');
Указание конкретных часовых поясов возможно с помощью:
use DateTimeZone;
TimeZone::make('time')
->listIdentifiers(DateTimeZone::ALL);
По умолчанию принимает значение `DateTimeZone::ALL`, но возможны и другие:
DateTimeZone::AFRICA;
DateTimeZone::AMERICA;
DateTimeZone::ANTARCTICA;
DateTimeZone::ARCTIC;
DateTimeZone::ASIA;
DateTimeZone::ATLANTIC;
DateTimeZone::AUSTRALIA;
DateTimeZone::EUROPE;
DateTimeZone::INDIAN;
DateTimeZone::PACIFIC;
DateTimeZone::UTC;
DateTimeZone::ALL_WITH_BC;
DateTimeZone::PER_COUNTRY;
С представлением переменных зон можно ознакомиться в документации [PHP](https://www.php.net/manual/ru/class.datetimezone.php)
.
[HTML редактор Quill](https://orchid.software/ru/docs/field/#html-redaktor-quill)
----------------------------------------------------------------------------------
Такой редактор позволяет вставлять рисунки, таблицы, указывать стили оформления текста, видео.
Пример записи:
Quill::make('html');
Доступно 6 групп элементов управления:
Quill::make('html')
->toolbar(["text", "color", "header", "list", "format", "media"]);
Можно установить дополнительные плагины с помощью простого Javascript файла:
document.addEventListener('orchid:quill', (event) => {
// Object for registering plugins
event.detail.quill;
// Parameter object for initialization
event.detail.options;
});
> **Примечание**: Вы можете добавлять пользовательские сценарии и таблицы стилей через файл конфигурации`platform.php`.
Пример для [quill-image-compress](https://github.com/benwinding/quill-image-compress)
:
В файле `config/platform.php` добавьте следующее в массив `resource.scripts` :
"https://unpkg.com/quill-image-compress@1.2.11/dist/quill.imageCompressor.min.js",
"/js/admin/quill.imagecropper.js",
В директории `public/js/admin` создайте файл `quill.imagecropper.js` со следующим содержимым:
document.addEventListener('orchid:quill', (event) => {
// Object for registering plugins
event.detail.quill.register("modules/imageCompressor", imageCompressor);
// Parameter object for initialization
event.detail.options.modules = {
imageCompressor: {
quality: 0.9,
maxWidth: 1000, // default
maxHeight: 1000, // default
imageType: 'image/jpeg'
}
};
});
[Markdown редактор](https://orchid.software/ru/docs/field/#markdown-redaktor)
------------------------------------------------------------------------------
Редактор для облегчённого языка разметки, созданный с целью написания максимально читаемого и удобного для правки текста, но пригодного для преобразования в языки для продвинутых публикаций.
 
Пример записи:
SimpleMDE::make('markdown');
[Matrix](https://orchid.software/ru/docs/field/#matrix)
--------------------------------------------------------
Поле предоставляет удобный интерфейс для редактирования плоской таблицы. Например, вы можете хранить информацию внутри столбца типа JSON:
Matrix::make('options')
->columns([\
'Attribute',\
'Value',\
'Units',\
])
Не всегда значения столбцов могут совпадать с тем, что нужно отображать в заголовках, для этого вы можете написать, используя ключи:
Matrix::make('options')
->columns([\
'Attribute' => 'attr',\
'Value' => 'product_value',\
])
Возможно указание максимального количества строк, при достижении которого кнопка добавления не будет доступна:
Matrix::make('options')
->columns(['id', 'name'])
->maxRows(10)
По умолчанию каждый элемент ячейки имеет поле textarea, но вы можете изменить его на свои собственные поля следующим образом:
Matrix::make('users')
->title('Users list')
->columns(['id', 'name'])
->fields([\
'id' => Input::make()->type('number'),\
'name' => TextArea::make(),\
]),
> **Примечание.** Матрица под капотом делает копирование полей на стороне клиента. Это хорошо работает для простых полей `input/select/etc`, но может не сработать для сложных или составных полей.
[Редактор кода](https://orchid.software/ru/docs/field/#redaktor-koda)
----------------------------------------------------------------------
Поле для записи программного кода с возможностью подсветки.

Пример записи:
Code::make('code');
Для указания подцветки кода под конкретный язык программирования можно использовать метод `language()`.
Code::make('code')
->language(Code::CSS);
Доступны следующие языки:
* Markup – `markup`, `html`, `xml`, `svg`, `mathml`
* CSS – `css`
* C-like – `clike`
* JavaScript – `javascript`, `js`
Поддерживается указание количества строк:
Code::make('code')
->lineNumbers();
[Cropper](https://orchid.software/ru/docs/field/#cropper)
----------------------------------------------------------
Позволяет загружать изображение и обрезать до нужного формата.

Пример записи:
Cropper::make('picture');
### [Ширина и высота](https://orchid.software/ru/docs/field/#sirina-i-vysota)
Для того чтобы контролировать формат, можно указать ширину и высоту необходимого изображения:
Cropper::make('picture')
->width(500)
->height(300);
Или вы можете установить определенные ограничения, используя `minWidth` / `maxWidth` или `minHeight` / `maxHeight` или использовать удобные методы `minCanvas` / `maxCanvas`
Cropper::make('picture')
->minCanvas(500)
->maxWidth(1000)
->maxHeight(800);
### [Ограничение размера файла](https://orchid.software/ru/docs/field/#ogranicenie-razmera-faila)
Для ограничения размера загружаемого файла необходимо задать максимальное значение в `MB`
Cropper::make('picture')
->maxFileSize(2);
### [Значение](https://orchid.software/ru/docs/field/#znacenie)
Контроль возвращаемого значения осуществляется с помощью методов:
Cropper::make('picture')
->targetId();
// 20
Будет возвращён порядковый номер (`id`) записи `Attachment`.
Cropper::make('picture')
->targetRelativeUrl();
// /storage/2024/11/12/0ae30560194b944c656c548becd371b15b22cfba.jpg
Вернёт относительный путь до изображения.
Cropper::make('picture')
->targetUrl();
// http://localhost/storage/2024/11/12/ade1a19e778ae64772a3e5348d32d5330c05893c.jpg
Вернёт абсолютный путь до изображения.
Cropper::make('picture')
->path('some_path');
// http://localhost/storage/some_path/69dc36c754411788a35a7e108d3b57396ddbcedc.jpg
Вернёт абсолютный путь до изображения, заменив path на своё значение
[Attach](https://orchid.software/ru/docs/field/#attach)
--------------------------------------------------------
Поле обеспечивает интуитивно понятный интерфейс для загрузки изображений и файлов, включая поддержку группировки и сортировки.
Для создания элемента загрузки файла используйте метод `make` класса `Attach`, указав имя поля:
use Orchid\Screen\Fields\Attach;
Attach::make('attachments');
Чтобы разрешить множественную загрузку файлов, используйте метод `multiple()`:
Attach::make('attachments')
->multiple();
### [Ограничение загружаемых файлов](https://orchid.software/ru/docs/field/#ogranicenie-zagruzaemyx-failov)
Для множественной загрузки с помощью метода `maxCount` можно задать максимальное количество файлов доступных для загрузки:
Attach::make('attachments')
->multiple()
->maxCount(3); // 3 файла
Также можно ограничить размер файлов с помощью метода `maxSize()`. Размер указывается в мегабайтах (MB):
Attach::make('attachments')
->maxSize(1024); // Размер в MB
> **Максимальный размер загружаемого файла:** По умолчанию значения `upload_max_filesize` и `post_max_size` равны 2M. Вы можете изменить эти параметры в `php.ini`, чтобы установить максимальный размер файлов больше 2M.
Используйте метод `accept`, чтобы определить типы файлов, которые должно принимать поле, например:
Attach::make('upload')
->accept('image/*,application/pdf,.psd');
Передаваемая строка представляет собой список [уникальных спецификаторов типов файлов](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers)
, разделённый запятыми.
### [Группировка файлов](https://orchid.software/ru/docs/field/#gruppirovka-failov)
Вы можете группировать файлы по различным категориям с помощью метода `group`. Это особенно полезно, если нужно загружать разные типы файлов, такие как документы и изображения.
Attach::make('docs')
->group('documents');
Attach::make('images')
->group('photo');
Для работы с загруженными файлами для которых укзывается группы через отношения модели используйте следующий синтаксис:
use Orchid\Attachment\Models\Attachment;
/**
* Возвращает прикрепленный "hero" (один к одному).
*/
public function hero(): HasOne
{
return $this->hasOne(Attachment::class, 'id', 'hero')
->withDefault();
}
/**
* Возвращает документы (многие ко многим).
* Загрузка осуществляется через метод group().
*/
public function documents(): MorphToMany
{
return $this->attachments('documents');
}
### [Работа с хранилищами файлов](https://orchid.software/ru/docs/field/#rabota-s-xranilishhami-failov)
Поле загрузки может работать с различными репозиториями. Для этого укажите ключ репозитория, указанный в `config/filesystems.php`:
Attach::make('upload')
->storage('s3');
По умолчанию используется хранилище `public`.
### [Явная настройка пути к файлам](https://orchid.software/ru/docs/field/#iavnaia-nastroika-puti-k-failam)
Если вам нужно игнорировать стандартные правила хранения файлов и явно указать путь для загрузки, используйте метод `path`:
Attach::make('upload')
->path('/custom/path');
### [Валидация и сортировка файлов на сервере](https://orchid.software/ru/docs/field/#validaciia-i-sortirovka-failov-na-servere)
Важно валидировать файлы и на серверной стороне. Например, проверить, что файл является изображением с определённым соотношением сторон или соответствующим типом. Для этого используйте метод `uploadUrl`, чтобы указать endpoint для загрузки файлов:
Attach::make('upload')
->uploadUrl(route('my.upload.endpoint'));
Точно так же можно указать endpoint для сортировки файлов:
Attach::make('upload')
->sortUrl(route('my.sort.endpoint'));
### [Обработка ошибок и вывод сообщений](https://orchid.software/ru/docs/field/#obrabotka-osibok-i-vyvod-soobshhenii)
Для того чтобы пользователи не сталкивались с неясными ошибками, важно предоставить чёткие и информативные сообщения об ошибках. Используйте методы `errorMaxSizeMessage` и `errorTypeMessage`, чтобы указать собственные сообщения:
Attach::make('upload')
->errorMaxSizeMessage("Размер файла слишком большой")
->errorTypeMessage("Неверный тип файла");
[Group](https://orchid.software/ru/docs/field/#group)
------------------------------------------------------
Компонент `Group` используется для объединения нескольких полей на одной строке, что позволяет создавать более компактные и организованные интерфейсы. Это особенно полезно для группировки связанных данных, таких как имя и фамилия.
Group::make([\
Input::make('first_name'),\
Input::make('last_name'),\
]),
### [Ширина колонок](https://orchid.software/ru/docs/field/#sirina-kolonok)
По умолчанию поля будут занимать всю доступную ширину экрана, если вы используете метод `fullWidth`. Этот вариант подходит для большинства случаев, когда вам нужно, чтобы элементы заполняли всё пространство:
Group::make([\
// ...\
])->fullWidth();
Однако в некоторых случаях вам может понадобиться, чтобы поля занимали только необходимое пространство. Метод `autoWidth` отлично подходит для ситуаций, когда поля содержат различный объем данных. Например, если вы используете радиокнопки:
Group::make([\
Radio::make('agreement')\
->placeholder('Yes')\
->value(1),\
\
Radio::make('contact')\
->placeholder('No')\
->value(0),\
])->autoWidth();
Для большей гибкости в настройке ширины колонок вы можете использовать метод `widthColumns()`, который поддерживает CSS Grid. Этот метод позволяет точно настраивать ширину колонок с использованием значений для свойства `grid-template-columns`:
Group::make([\
// ...\
])->widthColumns('2fr 1fr');
Допустимые значения для `widthColumns()` включают:
* Проценты (например, `30%`)
* Пиксели (например, `120px`)
* Доли (fractional units) (например, `2fr`)
* Другие значения, такие как `max-content` и `auto`
> **Важно:** Количество указанных значений не должно быть меньше числа элементов в группе.
Настройки ширины применяются только на десктопных устройствах. На мобильных устройствах каждое поле будет отображаться на новой строке, что улучшает отзывчивость интерфейса и делает его более удобным для пользователей.
### [Выравнивание колонок](https://orchid.software/ru/docs/field/#vyravnivanie-kolonok)
Колонки в группе могут иметь разную высоту, например, когда заголовок присутствует только в одной из них. Для создания более привлекательного интерфейса важно использовать выравнивание колонок.
Когда в одной из колонок есть заголовок, выравнивание всех колонок по нижнему краю родительского контейнера поможет сделать элементы более гармоничными. Для этого воспользуйтесь методом `alignEnd`:
Group::make([\
// ...\
])->alignEnd();
Когда вам нужно, чтобы все элементы располагались на одном уровне сверху, примените метод `alignStart`:
Group::make([\
// ...\
])->alignStart();
Чтобы обеспечить выравнивание колонок по базовой линии текста и добиться согласованности в отображении содержимого, используйте метод `alignBaseLine`:
Group::make([\
// ...\
])->alignBaseLine();
Для достижения симметричного вида центрируйте колонки с помощью метода `alignCenter`:
Group::make([\
// ...\
])->alignCenter();
[Кнопка](https://orchid.software/ru/docs/field/#knopka)
--------------------------------------------------------
Кнопки (`Button`) используются для отправки заполненной пользователем формы на сервер.
Чтобы создать кнопку, вызывающую метод `handler`, определённый в текущем экране, используйте `Button::make()`:
Button::make('Отправить')
->method('handler');
> Метод должен быть доступен в текущем экране, где размещена кнопка.
Если вам необходимо передать определённые данные в метод, укажите их вторым аргументом:
Button::make('Отправить')
->method('handler', [\
'user' => 1,\
]);
### [Подтверждение действия](https://orchid.software/ru/docs/field/#podtverzdenie-deistviia)
Для предотвращения случайных действий добавьте метод `confirm()`, который отобразит окно подтверждения перед выполнением операции. Это особенно полезно для необратимых действий, таких как удаление данных.
Button::make('Удалить')
->method('deleteItem')
->confirm('Вы потеряете доступ к этому элементу.');
> **Совет:** Указывайте в `confirm()` чёткое сообщение, чтобы пользователь понимал последствия.
Хорошее замечание! Действительно, в большинстве случаев `action()` будет использоваться для указания URL контроллера, а не какого-то внешнего адреса. Я скорректирую описание, чтобы оно лучше отражало этот момент. Вот обновлённый блок:
### [Указание URL для отправки данных](https://orchid.software/ru/docs/field/#ukazanie-url-dlia-otpravki-dannyx)
Для указания URL, куда должна отправляться форма, используйте метод `action()`. Обычно это будет URL контроллера в рамках вашего приложения, куда отправится запрос после нажатия кнопки.
Button::make('Отправить')
->action('https://orchid.software');
Button::make('Отправить')
->action(route('controller.method'));
### [Скачивание файла](https://orchid.software/ru/docs/field/#skacivanie-faila)
Для начала скачивания файла по нажатию кнопки примените метод `download()`. Он указывает системе, что результатом выполнения будет файл, который нужно загрузить, а не просто открыть в браузере.
Button::make('Скачать отчёт')
->method('export')
->download();
[Ссылка](https://orchid.software/ru/docs/field/#ssylka)
--------------------------------------------------------
Ссылки (`Link`) используются для перенаправления пользователя на другую страницу или выполнения действия, такого как скачивание файла.
Чтобы создать ссылку на определённый URL, используйте `Link::make()` с текстом ссылки и методом `href()`:
Link::make('Посетить Orchid')
->href('https://orchid.software');
### [Открытие ссылки в новой вкладке](https://orchid.software/ru/docs/field/#otkrytie-ssylki-v-novoi-vkladke)
Для открытия ссылки в новой вкладке добавьте метод `target('_blank')`. Это удобно для внешних ресурсов, которые нужно открыть параллельно с текущей страницей.
Link::make('Документация')
->href('https://orchid.software/docs')
->target('_blank');
### [Скачивание файла](https://orchid.software/ru/docs/field/#skacivanie-faila)
Если переход по ссылке должен инициировать скачивание файла, используйте метод `download()`. Это указывает браузеру, что ссылка ведёт к файлу для загрузки.
Link::make('Скачать отчёт')
->href('/path/to/report.pdf')
->download();
> **Примечание:** Убедитесь, что файл доступен по указанному пути, чтобы избежать ошибок при скачивании.
[Выпадающее меню (Dropdown)](https://orchid.software/ru/docs/field/#vypadaiushhee-meniu-dropdown)
--------------------------------------------------------------------------------------------------
`Dropdown` позволяет создать элемент с выпадающим списком действий, что удобно для группировки связанных действий под одной кнопкой, например, в меню управления элементом.
Чтобы создать меню, перечислите все действия в методе `list()`:
DropDown::make()
->icon('bs.options-vertical')
->list([\
Link::make('Редактировать')\
->route('platform.systems.users.edit', $user->id),\
\
Button::make('Удалить')\
->method('remove')\
->icon('trash'),\
]);
[NumberRange](https://orchid.software/ru/docs/field/#numberrange)
------------------------------------------------------------------
Вы можете создавать диапазоны чисел. Особенно полезно для фильтров.
NumberRange::make();
Использование с фильтрами:
TD::make()->filter(NumberRange::make())
//or
TD::make()->filter(TD::FILTER_NUMBER_RANGE)
Результатом является массив с ключами `min`, `max`.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Макеты группировки | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/grouping/# "Scroll to the top of the page")
Макеты группировки
==================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/grouping.md "View and edit this file on GitHub")
* [Аккордеон](https://orchid.software/ru/docs/grouping/#akkordeon)
* [Колонки](https://orchid.software/ru/docs/grouping/#kolonki)
* [Набор фильтров](https://orchid.software/ru/docs/grouping/#nabor-filtrov)
* [Табы](https://orchid.software/ru/docs/grouping/#taby)
* [Sortable](https://orchid.software/ru/docs/grouping/#sortable)
* [Подготовка базы данных](https://orchid.software/ru/docs/grouping/#podgotovka-bazy-dannyx)
* [Подготовка Eloquent модели](https://orchid.software/ru/docs/grouping/#podgotovka-eloquent-modeli)
* [Использование в экране](https://orchid.software/ru/docs/grouping/#ispolzovanie-v-ekrane)
[Аккордеон](https://orchid.software/ru/docs/grouping/#akkordeon)
-----------------------------------------------------------------
Аккордеоны полезны, когда Вы хотите переключаться между скрытием и отображением большого количества контента:

Аккордеоны поддерживают короткий синтаксис через вызов статического метода, что не требует создания отдельного класса:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::accordion([\
'Personal Information' => [\
Layout::rows([\
Input::make('user.name')\
->type('text')\
->required()\
->title('Name')\
->placeholder('Name'),\
\
Input::make('user.email')\
->type('email')\
->required()\
->title('Email')\
->placeholder('Email'),\
]),\
],\
'Billing Address' => [\
Layout::rows([\
Input::make('address')\
->type('text')\
->required()\
->title('Адрес доставки')\
->placeholder('Ул. Ленина дом 14 оф.162'),\
]),\
],\
]),\
];
}
Ключи будут использованы в качестве заголовков.
Обратите внимание, что Вы можете указывать в качестве значений и имя класса в нижнем регистре:
public function layout(): array
{
return [\
Layout::accordion([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
]),\
];
}
[Колонки](https://orchid.software/ru/docs/grouping/#kolonki)
-------------------------------------------------------------
Колонки полезны, когда Вам необходимо сгруппировать контент.

Колонки поддерживают короткий синтаксис через вызов статического метода, что не требует создания отдельного класса:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::columns([\
TableExample::class,\
RowExample::class,\
]),\
];
}
[Набор фильтров](https://orchid.software/ru/docs/grouping/#nabor-filtrov)
--------------------------------------------------------------------------
Для группировки фильтров, их сброса и применения, существует отдельный слой `Selection`, в котором они указываются.
Для создания исполните команду:
php artisan orchid:selection MySelection
Пример класса:
namespace App\Orchid\Layouts;
use Orchid\Platform\Filters\Filter;
use Orchid\Press\Http\Filters\CreatedFilter;
use Orchid\Press\Http\Filters\SearchFilter;
use Orchid\Screen\Layouts\Selection;
class MySelection extends Selection
{
/**
* @return Filter[]
*/
public function filters(): array
{
return [\
SearchFilter::class,\
CreatedFilter::class\
];
}
}
[Табы](https://orchid.software/ru/docs/grouping/#taby)
-------------------------------------------------------
Табы группируют контент и помогают в навигации. Полезны, когда Вы хотите переключаться между скрытием и отображением большого количества контента:

Табы поддерживают короткий синтаксис через вызов статического метода, что не требует создания отдельного класса:
use Orchid\Support\Facades\Layout;
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => [\
Layout::rows([\
Input::make('user.name')\
->type('text')\
->required()\
->title('Name')\
->placeholder('Name'),\
\
Input::make('user.email')\
->type('email')\
->required()\
->title('Email')\
->placeholder('Email'),\
]),\
],\
'Billing Address' => [\
Layout::rows([\
Input::make('address')\
->type('text')\
->required()\
->title('Адрес доставки')\
->placeholder('Ул. Ленина дом 14 оф.162'),\
]),\
],\
]),\
];
}
Ключи будут использованы в качестве заголовков.
Обратите внимание, что Вы можете указывать в качестве значений и строчное имя класса:
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
]),\
];
}
По умолчанию активной является либо первая, либо последняя активная вкладка. сли вам нужно явно определить активную вкладку, вы можете сделать это с помощью метода `->activeTab($key)`:
public function layout(): array
{
return [\
Layout::tabs([\
'Personal Information' => PersonalInformationRow::class,\
'Billing Address' => BillingAddressRow::class,\
])->activeTab('Billing Address'),\
];
}
[Sortable](https://orchid.software/ru/docs/grouping/#sortable)
---------------------------------------------------------------
Sortable в платформе Orchid упрощает управление порядком элементов в вашем приложении. Вы сможете легко изменить порядок элементов в вашем списке и создавать интерактивные пользовательские интерфейсы путем простой функции перетаскивания (Drag & Drop) Это значительно облегчает работу с порядковыми элементами в пользовательском интерфейсе.
### [Подготовка базы данных](https://orchid.software/ru/docs/grouping/#podgotovka-bazy-dannyx)
Для начала использования функциональности сортировки, вам необходимо подготовить базу данных. Для этого создайте миграцию, которая добавит простую целочисленную колонку в таблицу, с которой вы планируете работать. Вот пример миграции:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOrderColumnToTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('table_name', function (Blueprint $table) {
$table->integer('order')->default(1);
});
}
// ...
}
Замените `table_name` на имя таблицы, к которой нужно добавить колонку. Также вы можете выбрать любое другое имя для колонки, заменив `'order'` на предпочитаемое.
> Не забудьте выполнить миграцию с помощью команды `php artisan migrate`, чтобы добавить новую колонку в базу данных.
### [Подготовка Eloquent модели](https://orchid.software/ru/docs/grouping/#podgotovka-eloquent-modeli)
После настройки базы данных и миграций добавьте трейт `Sortable` к вашей модели:
use Illuminate\Database\Eloquent\Model;
use Orchid\Platform\Concerns\Sortable;
class Idea extends Model
{
use Sortable;
//...
}
> Примечание: Обратите внимание, что необходимо импортировать класс модели Eloquent, а затем использовать трейт `Sortable`.
Если имя колонки отличается от `order`, можно добавить метод `getSortColumnName()` в вашу модель, чтобы явно указать имя колонки:
use Illuminate\Database\Eloquent\Model;
use Orchid\Platform\Concerns\Sortable;
class Idea extends Model
{
use Sortable;
//...
/**
* Get the column name for sorting.
*
* @return string
*/
public function getSortColumnName(): string
{
return 'sort';
}
}
### [Использование в экране](https://orchid.software/ru/docs/grouping/#ispolzovanie-v-ekrane)
Теперь у нас есть подготовленная модель с функцией сортировки. Давайте создадим графический интерфейс для drag&drop сортировки, в методе `query()` вашего экрана укажите список моделей, который будет отображаться для сортировки:
use App\Models\Idea;
use Orchid\Screen\Repository;
public function query(): array
{
return [\
'models' => Idea::sorted()->get(),\
];
}
Здесь мы используем метод `sorted()`, предоставляемый трейтом `Sortable`, чтобы получить отсортированный список моделей. Он так же имеет необязательный аргумент – направление сортировки (ASC – по возрастанию, DESC – по убыванию). По умолчанию установлено значение ASC.
В методе `layout()` вашего экрана добавим графический интерфейс с использованием слоя `Layout::sortable()`:
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Sight;
public function layout(): iterable
{
return [\
Layout::sortable('models', [\
Sight::make('title'),\
]),\
];
}
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Icons | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/icons/# "Scroll to the top of the page")
Icons
=====
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/icons.md "View and edit this file on GitHub")
Пакет поставляется с набором иконок, которые можно найти на сайте [Bootstrap Icons](https://icons.getbootstrap.com/)
. Эти иконки имеют префикс `bs.*`, который используется как префикс для идентификации иконок в вашем коде.
> Если вы ищете список иконок для предыдущих версий, посетите страницу [Orchid Icon Pack](https://orchid.software/ru/docs/orchid-icons)
> .
[Custom Icons](https://orchid.software/ru/docs/icons/#custom-icons)
--------------------------------------------------------------------
Допустим, мы хотим добавить иконку из популярного Font Awesome. Для этого выберите подходящий каталог хранения, например, создайте новый каталог `icons` и подкаталог `fontawesome`:
resources
- css
- icons
-- fontawesome
- js
- lang
- views
Загрузите в новый каталог соответствующие значки, например, этот [значок блокнота](https://github.com/FortAwesome/Font-Awesome/blob/ce084cb3463f15fd6b001eb70622d00a0e43c56c/svgs/solid/address-book.svg)
. Затем укажите каталог, в котором нам нужно искать наши изображения, для этого отредактируйте файл конфигурации `config/platform.php`:
'icons' => [\
'fa' => resource_path('icons/fontawesome')\
],
Все, что мы здесь сделали, это объявили префикс, по которому мы будем обращаться к fa и каталог, в котором расположены файлы. Для отображения в компонентах пакета нужно передать только префикс + имя. Например, определение иконки в меню будет выглядеть так:
Menu::make('Example of custom icons')
->icon('fa.address-book')
->url(#);
Вы также можете использовать иконки вне панели администратора [с помощью компонента Blade](https://github.com/orchidsoftware/blade-icons)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Использование JavaScript | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/javascript/# "Scroll to the top of the page")
Использование JavaScript
========================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/javascript.md "View and edit this file on GitHub")
* [Turbo](https://orchid.software/ru/docs/javascript/#turbo)
* [Stimulus](https://orchid.software/ru/docs/javascript/#stimulus)
* [Обертка Vue.js внутри Stimulus](https://orchid.software/ru/docs/javascript/#obertka-vuejs-vnutri-stimulus)
Основой платформы по части стилей является [Bootstrap](http://getbootstrap.com/)
, а в браузере выполняется код [Hotwired](https://hotwired.dev/)
. Вы можете подключить другие библиотеки по своему вкусу, но мы рекомендуем оставаться в этой экосистеме.
[Turbo](https://orchid.software/ru/docs/javascript/#turbo)
-----------------------------------------------------------
Благодаря [Turbo](https://turbo.hotwire.dev/)
админ-панель эмулирует Single Page Application, загружая ресурсы только при первом вызове и создавая впечатление повторной отрисовки контента в браузере вместо стандартных переходов между страницами.
Поскольку все ресурсы будут загружены при первом вызове, классические вызовы, подобные этому, работать не будут:
document.addEventListener("load", () => {
console.log('Page load');
});
Он будет выполнен только один раз и больше не будет вызываться при переходах. Чтобы этого избежать, нужно использовать события turbo:
document.addEventListener("turbo:load", () => {
console.log('Page load');
})
Более подробную информацию вы можете найти на сайте [turbo.hotwire.dev](https://turbo.hotwire.dev/)
.
[Stimulus](https://orchid.software/ru/docs/javascript/#stimulus)
-----------------------------------------------------------------
[Stimulus](https://stimulus.hotwired.dev/)
это фреймворк JavaScript от разработчиков Ruby on Rails. Он оснащает фронтенд-разработку новыми подходами к JavaScript, при этом не стремится контролировать все ваши действия и не навязывает отделение фронтенда от бэкенда.
Построим базовый пример, который отображает текст, введённый в поле. Для этого выполним описанные ниже действия.
В `resources/js` создадим следующую структуру:
resources
├── js
│ ├── controllers
│ │ └── hello.js
│ └── dashboard.js
├── lang
├── sass
└── views
Класс контроллера со следующим содержанием:
// hello.js
export default class extends window.Controller {
static get targets() {
return [ "name", "output" ]
}
greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}
И точку сборки:
// dashboard.js
import HelloController from "./controllers/hello"
application.register("hello", HelloController);
Такая структура не помешает вашему приложению не зависимо от того, какой front-end строится: Angular/React/Vue и т.п.
Останется только описать сборку в webpack.mix.js :
let mix = require('laravel-mix');
mix.js('resources/js/dashboard.js', 'public/js')
Осталось только подключить полученный сценарий к панели в файле конфигурации или в сервис провайдере, используя метод `registerResource`. Точно так же можно поступить и с таблицами стилей, что позволит эффективно строить логику приложений.
// config/platform.php
'resource' => [\
'stylesheets' => [],\
'scripts' => [\
'/js/dashboard.js'\
],\
],
> **Примечание**. Для применения изменений в конфигурационном файле может потребоваться очистить кеш, если он был создан ранее. Это можно сделать с помощью artisan команды `artisan config:clear`.
Пример записи для поставщика услуг
// app/Providers/AppServiceProvider.php
use Orchid\Platform\Dashboard;
class AppServiceProvider extends ServiceProvider
{
public function boot(Dashboard $dashboard)
{
$dashboard->registerResource('scripts','/js/dashboard.js');
//$dashboard->registerResource('stylesheets','/css/dashboard.css');
}
}
Для отображения воспользуемся шаблоном, для которого предварительно нужно определить `Controller` и `Route` в вашем приложение:
// hello.blade.php
[Обертка Vue.js внутри Stimulus](https://orchid.software/ru/docs/javascript/#obertka-vuejs-vnutri-stimulus)
------------------------------------------------------------------------------------------------------------
Многие разработчики любят простоту и мощность Vue.js для построения интерактивных и отзывчивых frontend приложений. В этой секции, мы рассмотрим как просто обернуть и интегрировать Vue компонент внутри Stimulus контроллера.
Создайте файл Stimulus контроллера, для примера `hello_controller.js`:
import {createApp} from 'vue';
export default class extends window.Controller {
connect() {
this.app = createApp({
data() {
return {
message: 'Hello, Vue.js!'
}
}
});
this.app.mount(this.element);
}
disconnect() {
this.app.unmount();
}
}
Укажите ваш контроллер во view, а конкретно в blade шаблоне:
@{{ message }}
Теперь, когда вы перезагрузите страницу, экземпляр Vue.js будет создан и мы увидим наше сообщение \`Hello, Vue.js!' на экране и внутри HTML элемента. Далее вы можете использывать Vue.js как обычно в рамках контроллера Stimulus.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Установка платформы | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/installation/# "Scroll to the top of the page")
Установка платформы
===================
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/installation.md "View and edit this file on GitHub")
* [Создать проект](https://orchid.software/ru/docs/installation/#sozdat-proekt)
* [Добавить зависимость](https://orchid.software/ru/docs/installation/#dobavit-zavisimost)
* [Установка пакета](https://orchid.software/ru/docs/installation/#ustanovka-paketa)
* [Создание пользователя](https://orchid.software/ru/docs/installation/#sozdanie-polzovatelia)
* [Запуск локального сервера](https://orchid.software/ru/docs/installation/#zapusk-lokalnogo-servera)
* [Обновление](https://orchid.software/ru/docs/installation/#obnovlenie)
* [Обновление ресурсов](https://orchid.software/ru/docs/installation/#obnovlenie-resursov)
* [Что делать дальше?](https://orchid.software/ru/docs/installation/#cto-delat-dalse)
Прежде чем вы сможете использовать пакет, нужно будет установить ее. Это руководство поможет вам выполнить простую установку, чтобы запустить проект.
[Создать проект](https://orchid.software/ru/docs/installation/#sozdat-proekt)
------------------------------------------------------------------------------
> **Примечание.** Если у вас уже установлен Laravel, вы можете пропустить этот шаг..
Платформа является пакетом для фреймворка Laravel, необходимо сначала установить его. Это можно сделать с помощью инструмента управления зависимостями Composer, выполнив в терминале команду `composer create-project`:
$ composer create-project laravel/laravel orchid-project "12.*"
Или, если вы предпочитаете установщик Laravel:
$ laravel new orchid-project
Для получения дополнительной информации о том, как установить Laravel, используйте [Официальное руководство по установке laravel](https://laravel.com/docs/installation)
.
> **У вас нет Composer?** Его легко установить, следуя инструкциям на странице [загрузки](https://getcomposer.org/download/)
> .
Это создаст новый каталог `orchid-project`, загрузит в него зависимости и сгенерирует основные каталоги и файлы, которые понадобятся для начала работы. Другими словами, установит ваш новый проект фреймворка.
**Не забывайте**
* Установить права «chmod -R o+w» на каталоги `storage` и `bootstrap/cache`
* Отредактировать `.env` файл
[Добавить зависимость](https://orchid.software/ru/docs/installation/#dobavit-zavisimost)
-----------------------------------------------------------------------------------------
Перейдите в созданный каталог проекта и выполните команду:
$ composer require orchid/platform
> **Примечание.** Если вы устанавливали Laravel иначе, то возможно, вам придется сгенерировать ключ используя комманду `php artisan key:generate`
> **Примечание.** Вам также необходимо создать новую базу данных и обновить `.env` файл с учетными данными и добавить URL-адрес вашего приложения в переменную `APP_URL`.
[Установка пакета](https://orchid.software/ru/docs/installation/#ustanovka-paketa)
-----------------------------------------------------------------------------------
> **Примечание:** При установке пакета произойдет перезапись модели `app/Models/User`. Однако важно отметить, что замена модели не является обязательной. Вы всегда можете самостоятельно настроить модель по своему усмотрению. Пакет автоматически применяет некоторые настройки, например, `hidden` и `casts` для модели Eloquent.
Запустим процесс установки, выполнив команду:
php artisan orchid:install
[Создание пользователя](https://orchid.software/ru/docs/installation/#sozdanie-polzovatelia)
---------------------------------------------------------------------------------------------
Для создания пользователя с максимальными правами на текущий момент, необходимо выполнить команду передав имя пользователя, электронный адрес и пароль:
php artisan orchid:admin
[Запуск локального сервера](https://orchid.software/ru/docs/installation/#zapusk-lokalnogo-servera)
----------------------------------------------------------------------------------------------------
Для запуска проекта можно использовать встроенный сервер:
php artisan serve
Откройте браузер и перейдите к `http://localhost:8000/admin`. Если все работает, вы увидите страницу входа в панель управления. Позже, когда вы закончите работу, остановите сервер, нажав `Ctrl+C` в используемом терминале.
> **Примечание.** Если используемая среда выполнения настроена на другой домен (например orchid.loc), то панель администратора будет недоступна. В этом случае требуется указать используемый домен в файле конфигурации `config/platform.php` или в `.env`. Это позволяет делать доступной панель администратора на другом домене или поддомене, например `platform.example.com`.
[Обновление](https://orchid.software/ru/docs/installation/#obnovlenie)
-----------------------------------------------------------------------
Находясь в директории проекта используйте `Composer` для обновления пакета:
composer update orchid/platform --with-dependencies
> **Примечание.** Вы так же можете обновить все ваши зависимости, перечисленные в файле `composer.json`, выполнив команду `composer update`.
После обновления до новой версии обязательно обновите ресурсы JavaScript и CSS, используя `orchid:publish` и очистите все кешированные представления с помощью `view:clear`.
php artisan orchid:publish
php artisan view:clear
[Обновление ресурсов](https://orchid.software/ru/docs/installation/#obnovlenie-resursov)
-----------------------------------------------------------------------------------------
Чтобы обеспечить обновление ресурсов при загрузке новой версии, вы можете добавить хук Composer в файл `composer.json` файл вашего проекта для автоматической публикации последних ресурсов:
"scripts": {
"post-update-cmd": [\
"@php artisan orchid:publish --ansi"\
]
}
> **Возникли проблемы во время установки?** Возможно, что у кого-то уже была такая проблема [https://github.com/orchidsoftware/platform/issues](https://github.com/orchidsoftware/platform/issues)
> . Если нет, вы можете отправить сообщение или обратиться за [помощью](https://github.com/orchidsoftware/platform/issues/new)
> .
[Что делать дальше?](https://orchid.software/ru/docs/installation/#cto-delat-dalse)
------------------------------------------------------------------------------------
Установленный пакет уже имеет несколько экранов, на которых показаны различные поля ввода, маски, состояния, а также некоторая компоновка интерфейса. Вы можете попробовать их или сразу перейти к пошаговым примерам работы с пакетом на странице [“Быстрый старт”](https://orchid.software/ru/docs/quickstart)
или просто погрузиться в [документацию](https://orchid.software/ru/docs/screens)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Legend | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/legend/# "Scroll to the top of the page")
Legend
======
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/legend.md "View and edit this file on GitHub")
Макет легенда используется для просмотра одной модели:

Легенда поддерживает краткое написание без создания отдельного класса, например:
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Sight;
public function layout(): array
{
return [\
Layout::legend('user', [\
Sight::make('id'),\
Sight::make('name'),\
Sight::make('email'),\
]),\
];
}
Ожидается, что первый аргумент получит ключ, указанный в методе запроса экрана, который должен быть массивом или моделью. А второй — столбцы которые требуется отобразить.
Многие методы у класса `Sight` класса общие с `TD` (используется в [таблице](https://orchid.software/en/docs/table/)
). Например, можно добавить пояснение:
Layout::legend('user', [\
Sight::make('id')->popover('Unique number in the system'),\
]),
Для того, чтобы использовать собственный шаблон или выполнить дополнительную обработку, вы можете использовать замыкание, переданное в метод `render` :
Layout::legend('user', [\
Sight::make('id')->render(function (){\
return 'Any html';\
}),\
]),
Если такая обработка нужна часто, то более подходящим решением будет создать `Blade компонент` ([Подробнее](https://laravel.com/docs/blade#components)
) и указать его:
Layout::legend('user', [\
Sight::make('id')->component(IdInformation::class),\
]),
Компоненты работают так же, как таблица. Вы можете увидеть больше примеров [здесь](https://orchid.software/ru/docs/table#components)
.
Our Friends
[](https://assisted-mindfulness.com/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://sajya.github.io/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
[](https://laravel.su/?utm_source=orchid&utm_medium=docs&utm_campaign=friends)
---
# Listener | Orchid - Laravel Admin Panel
 
[](https://orchid.software/ru/docs/listener/# "Scroll to the top of the page")
Listener
========
[Suggest Edit](https://github.com/orchidsoftware/orchid.software/edit/master/docs/ru/docs/listener.md "View and edit this file on GitHub")
`Listener` макет – особый тип макета, который используется для обновления отображаемых данных на экране в ответ на ввод пользователя. Это полезно, когда вы хотите создать динамические и интерактивные экраны, способные изменять свой вид и поведение в зависимости от действий пользователя.
В этом примере у нас есть экран с двумя полями ввода для чисел, которые должны быть вычтены друг из друга. Мы можем сделать это с помощью макета слушателя (listener layout).
Для создания макета слушателя вам необходимо выполнить следующую команду `artisan` в вашем терминале:
php artisan orchid:listener SubtractListener
Эта команда создаст новый класс с именем `SubtractListener` в директории `app/Orchid/Layouts`.
Выполнение вышеприведенной команды создаст новый класс с именем `SubtractListener` в директории `app/Orchid/Layouts`. После создания вы можете добавить необходимые поля в методе `layouts`, как показано ниже:
namespace App\Orchid\Layouts;
use Illuminate\Http\Request;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Layouts\Listener;
use Orchid\Screen\Repository;
use Orchid\Support\Facades\Layout;
class SubtractListener extends Listener
{
/**
* Список имен полей, значения которых будут отслеживаться.
*
* @var string[]
*/
protected $targets = [];
/**
* @return Layout[]
*/
protected function layouts(): array
{
return [\
Layout::rows([\
Input::make('minuend')\
->title('Первый аргумент')\
->type('number'),\
\
Input::make('subtrahend')\
->title('Второй аргумент')\
->type('number'),\
]),\
];
}
/**
* @param \Orchid\Screen\Repository $repository
* @param \Illuminate\Http\Request $request
*
* @return \Orchid\Screen\Repository
*/
public function handle(Repository $repository, Request $request): Repository
{
return $repository;
}
}
Здесь свойство `targets` содержит имена полей, для которых требуется действие при изменении. В нашем примере поля с именами `minuend` и `subtrahend` считаются целевыми:
/**
* Список имен полей, значения которых будут отслеживаться.
*
* @var string[]
*/
protected $targets = [\
'minuend',\
'subtrahend',\
];
> **Примечание**. Множественные поля выбора, такие как `