### Pie Chart Setup with Labels and Datasets
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Defines a pie chart with both labels and dataset values specified directly within the `setup()` method. This example does not use AJAX.
```php
chart = new Chart();
$this->chart->dataset('Red', 'pie', [10, 20, 80, 30])
->backgroundColor([
'rgb(70, 127, 208)',
'rgb(77, 189, 116)',
'rgb(96, 92, 168)',
'rgb(255, 193, 7)',
]);
// OPTIONAL
$this->chart->displayAxes(false);
$this->chart->displayLegend(true);
// MANDATORY. Set the labels for the dataset points
$this->chart->labels(['HTML', 'CSS', 'PHP', 'JS']);
}
}
```
--------------------------------
### Setup Show Operation - Default Columns
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-show
Manually define columns in `setupShowOperation()` to stop default guessing and removing. This provides complete control over displayed columns, starting from a blank slate.
```php
// if you just want to show the same columns as inside ListOperation
protected function setupShowOperation()
{
$this->setupListOperation();
}
```
--------------------------------
### Chart Controller Setup with AJAX Loading
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Example ChartController setup that initializes a chart and configures it to load data via AJAX. It sets labels and specifies the AJAX endpoint.
```php
chart = new Chart();
// MANDATORY. Set the labels for the dataset points
$labels = [];
for ($days_backwards = 30; $days_backwards >= 0; $days_backwards--) {
if ($days_backwards == 1) {
}
$labels[] = $days_backwards.' days ago';
}
$this->chart->labels($labels);
// RECOMMENDED.
// Set URL that the ChartJS library should call, to get its data using AJAX.
$this->chart->load(backpack_url('charts/new-entries'));
// OPTIONAL.
$this->chart->minimalist(false);
$this->chart->displayLegend(true);
}
/**
* Respond to AJAX calls with all the chart data points.
*
* @return json
*/
public function data()
{
for ($days_backwards = 30; $days_backwards >= 0; $days_backwards--) {
// Could also be an array_push if using an array rather than a collection.
$users[] = User::whereDate('created_at', today()
->subDays($days_backwards))
->count();
$articles[] = Article::whereDate('created_at', today()
->subDays($days_backwards))
->count();
$categories[] = Category::whereDate('created_at', today()
->subDays($days_backwards))
->count();
$tags[] = Tag::whereDate('created_at', today()
->subDays($days_backwards))
->count();
}
$this->chart->dataset('Users', 'line', $users)
->color('rgb(77, 189, 116)')
->backgroundColor('rgba(77, 189, 116, 0.4)');
$this->chart->dataset('Articles', 'line', $articles)
->color('rgb(96, 92, 168)')
->backgroundColor('rgba(96, 92, 168, 0.4)');
$this->chart->dataset('Categories', 'line', $categories)
->color('rgb(255, 193, 7)');
```
--------------------------------
### Run Backpack Installation Command
Source: https://backpackforlaravel.com/docs/7.x/installation
After requiring the package, run the Artisan installation command. This command is interactive and will guide you through the setup process.
```bash
php artisan backpack:install
```
--------------------------------
### Full Custom Auth and Dashboard Routes Setup
Source: https://backpackforlaravel.com/docs/7.x/base-how-to
When both 'setup_auth_routes' and 'setup_dashboard_routes' are set to false, you must manually register all routes. This example provides a starting point for custom routes.
```php
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix'), 'namespace' => 'Backpack\Base\app\Http\Controllers'], function () {
Route::auth();
Route::get('logout', 'Auth\LoginController@logout');
Route::get('dashboard', 'AdminController@dashboard');
Route::get('/', 'AdminController@redirect');
});
```
--------------------------------
### Run FileManager Installation Artisan Command
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
After installing the package, run this Artisan command to complete the setup. This typically publishes assets and configures the package.
```bash
php artisan backpack:filemanager:install
```
--------------------------------
### Advanced Datagrid Configuration
Source: https://backpackforlaravel.com/docs/7.x/base-components
This example demonstrates advanced customization of a datagrid, allowing removal of buttons and widgets via the ':setup' closure. It's useful for fine-tuning the datagrid's appearance and functionality.
```blade
```
--------------------------------
### Install Settings Package
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Install the Settings package using Composer, publish its service provider and migrations, and run the migrations.
```bash
# install the package
composer require backpack/settings
# run the migration
php artisan vendor:publish --provider="Backpack\Settings\SettingsServiceProvider"
php artisan migrate
```
--------------------------------
### Install a Backpack Theme
Source: https://backpackforlaravel.com/docs/7.x/crud-how-to
After manual installation, install one of the provided first-party themes like Tabler, CoreUI v4, or CoreUI v2. Finally, check if assets are correctly used.
```bash
# then install ONE of the first-party themes:
php artisan backpack:require:theme-tabler php artisan backpack:require:theme-coreuiv4 php artisan backpack:require:theme-coreuiv2
# then check assets can be correctly used
php artisan basset:check
```
--------------------------------
### Installation and Debugging Commands
Source: https://backpackforlaravel.com/docs/7.x/generating-code
Utilities for installing Backpack, managing dependencies, and fixing common issues.
```bash
php artisan backpack:install
```
```bash
php artisan backpack:require:pro
```
```bash
php artisan backpack:require:devtools
```
```bash
php artisan backpack:require:editablecolumns
```
```bash
php artisan backpack:publish-middleware
```
```bash
php artisan backpack:fix
```
```bash
php artisan backpack:user
```
```bash
php artisan backpack:version
```
--------------------------------
### Setup Show Operation - Add Widgets
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-show
Integrate custom content, cards, charts, or notices into the show operation using widgets. Widgets can be added to `before_content` or `after_content` sections. This example demonstrates adding row-based widgets and external scripts/styles.
```php
public function setupShowOperation()
{
// dynamic data to render in the following widget
$userCount = \App\Models\User::count();
//add div row using 'div' widget and make other widgets inside it to be in a row
Widget::add()->to('before_content')->type('div')->class('row')->content([
//widget made using fluent syntax
Widget::make()
->type('progress')
->class('card border-0 text-white bg-primary')
->progressClass('progress-bar')
->value($userCount)
->description('Registered users.')
->progress(100 * (int)$userCount / 1000)
->hint(1000 - $userCount . ' more until next milestone.'),
//widget made using the array definition
Widget::make(
[
'type' => 'card',
'class' => 'card bg-dark text-white',
'wrapper' => ['class' => 'col-sm-3 col-md-3'],
'content' => [
'header' => 'Example Widget',
'body' => 'Widget placed at "before_content" secion in same row',
]
]
),
]);
//you can also add Script & CSS to your page using 'script' & 'style' widget
Widget::add()->type('script')->stack('after_scripts')->content('https://code.jquery.com/ui/1.12.0/jquery-ui.min.js');
Widget::add()->type('style')->stack('after_styles')->content('https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.0.0-beta.58/dist/themes/light.css');
}
```
--------------------------------
### Setup Show Operation - Auto Setup and Custom Columns
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-show
Allows Backpack to guess columns while enabling custom additions before or after. Call `autoSetupShowOperation()` and then define or remove columns as needed.
```php
// show whatever you want
protected function setupShowOperation()
{
// MAYBE: do stuff before the autosetup
// automatically add the columns
$this->autoSetupShowOperation();
// MAYBE: do stuff after the autosetup
// for example, let's add some new columns
CRUD::column([
'name' => 'my_custom_html',
'label' => 'Custom HTML',
'type' => 'custom_html',
'value' => 'Something',
]);
// in the following examples, please note that the table type is a PRO feature
CRUD::column([
'name' => 'table',
'label' => 'Table',
'type' => 'table',
'columns' => [
'name' => 'Name',
'desc' => 'Description',
'price' => 'Price',
]
]);
CRUD::column([
'name' => 'fake_table',
'label' => 'Fake Table',
'type' => 'table',
'columns' => [
'name' => 'Name',
'desc' => 'Description',
'price' => 'Price',
],
]);
// or maybe remove a column
CRUD::column('text')->remove();
}
```
--------------------------------
### Basic Fetch Operation Setup
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-fetch
Use the `FetchOperation` trait and define a `fetchEntityName()` method to enable AJAX fetching for a related entity. This example shows fetching `Tag` models.
```php
use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
protected function fetchTag()
{
return $this->fetch(\'App\Models\Tag::class);
}
```
--------------------------------
### Basic List Operation Setup
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-list-entries
Use the ListOperation trait on your controller and define columns in setupListOperation().
```php
chart = new Chart();
// OPTIONAL
$this->chart->displayAxes(false);
$this->chart->displayLegend(false);
// MANDATORY. Set the chart title
$this->chart->title('Sample Chart');
// MANDATORY. Set the chart subtitle
$this->chart->subtitle('This is a simple example.');
// MANDATORY. Set the labels for the dataset points
$this->chart->labels(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']);
// MANDATORY. Set the datasets for the chart
$this->chart->dataset('Sample Data 1', 'line', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
->color('rgba(255, 193, 7, 1)')
->backgroundColor('rgba(255, 193, 7, 0.4)');
$this->chart->dataset('Tags', 'line', $tags)
->color('rgba(70, 127, 208, 1)')
->backgroundColor('rgba(70, 127, 208, 0.4)');
}
}
```
--------------------------------
### Install BackupManager Package
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Install the BackupManager package using Composer, publish its configuration and language files, and optionally add a menu item.
```bash
composer require backpack/backupmanager
php artisan vendor:publish --provider="Backpack\BackupManager\BackupManagerServiceProvider"
php artisan backpack:add-menu-content ""
```
--------------------------------
### Define Show Operation Routes
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
Example of defining routes for the 'show' operation within a CrudController. This method is called during route setup.
```php
protected function setupShowRoutes($segment, $routeName, $controller)
{
Route::get($segment.'/{id}/show', [
'as' => $routeName.'.show',
'uses' => $controller.'@show',
'operation' => 'show',
]);
}
```
--------------------------------
### Install Backpack with Debugging and Increased Timeout
Source: https://backpackforlaravel.com/docs/7.x/installation
To troubleshoot installation errors, run this command with the `--debug` flag to see more detailed output, along with an increased timeout.
```bash
php artisan backpack:install --timeout=600 --debug
```
--------------------------------
### Hook into Specific Operation Event
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
Add a button to the CRUD panel during the 'create' operation's setup phase. This example hooks into the 'create:before_setup' event.
```php
LifecycleEvent::hookInto(['create:before_setup'], function() {
$this->crud->addButton('top', 'create', 'view', 'crud::buttons.create');
});
```
--------------------------------
### Install Composer Dependencies
Source: https://backpackforlaravel.com/docs/7.x/demo
Install all project dependencies using Composer after configuring private repository access.
```bash
composer install
```
--------------------------------
### Conditional Operation Setup
Source: https://backpackforlaravel.com/docs/7.x/crud-api
Use the operation() method within setup() to apply specific configurations only when a particular operation is active.
```php
public function setup() {
// ...
$this->crud->operation('list', function() {
$this->crud->addColumn('name');
});
}
```
--------------------------------
### Manual Backpack CRUD Installation Commands
Source: https://backpackforlaravel.com/docs/7.x/crud-how-to
Execute these commands in your terminal for a manual installation of Backpack CRUD if automatic installation fails. This includes publishing service providers and middleware.
```bash
composer require backpack/crud
php artisan vendor:publish --provider="Backpack\CRUD\BackpackServiceProvider" --tag="minimum"
php artisan migrate
php artisan backpack:publish-middleware
composer require --dev backpack/generators
php artisan basset:install --no-check --no-interaction
```
--------------------------------
### Install LogManager Package
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Install the LogManager package via Composer and add a 'storage' filesystem disk to your config/filesystems.php.
```bash
composer require backpack/logmanager
```
```php
// used for Backpack/LogManager
'storage' => [
'driver' => 'local',
'root' => storage_path(),
],
```
--------------------------------
### Install Package Using Composer with --prefer-source
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-using-the-addon-skeleton
Install your package using Composer with the --prefer-source flag. This ensures that the actual GitHub repository is pulled, allowing for direct interaction with the package's code within your project's vendor directory.
```bash
composer require vendor-name/package-name --prefer-source
```
--------------------------------
### Install Backpack FileManager
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Install the FileManager package using Composer. This command downloads the package files into your project.
```bash
composer require backpack/filemanager
```
--------------------------------
### Install and Run Laracasts Generators
Source: https://backpackforlaravel.com/docs/7.x/crud-tutorial
Install the laracasts/generators package to help create database migrations and run them. This is a prerequisite for generating the database table.
```bash
composer require --dev laracasts/generators
php artisan make:migration:schema create_tags_table --schema="name:string:unique"
php artisan migrate
```
--------------------------------
### Install Backpack with Increased Timeout
Source: https://backpackforlaravel.com/docs/7.x/installation
If the installation process times out, use this command to increase the timeout duration. The `--timeout=600` flag sets the timeout to 10 minutes.
```bash
php artisan backpack:install --timeout=600
```
--------------------------------
### Install Laravel Packager
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-using-the-addon-skeleton
Installs the jeroen-g/laravel-packager package for managing Laravel packages.
```bash
composer require jeroen-g/laravel-packager --dev
```
--------------------------------
### Setup CRUD Operations with Closures
Source: https://backpackforlaravel.com/docs/7.x/crud-tutorial
Configure CRUD model, route, entity names, columns, and fields within operation closures in the setup() method. This approach ensures configurations are applied only to specific operations.
```php
public function setup()
{
CRUD::setModel('App\Models\Tag');
CRUD::setRoute(config('backpack.base.route_prefix') . '/tag');
CRUD::setEntityNameStrings('tag', 'tags');
CRUD::operation('list', function() {
CRUD::column('name');
});
CRUD::operation(['create', 'update'], function() {
CRUD::addValidation(TagCrudRequest::class);
CRUD::field('name');
});
}
}
```
--------------------------------
### Install laracasts/generators
Source: https://backpackforlaravel.com/docs/7.x/getting-started-basics
Install the laracasts/generators package as a development dependency to assist in creating migrations.
```bash
# STEP 0. install a 3d party tool to generate migrations
composer require --dev laracasts/generators
```
--------------------------------
### Add Settings Menu Item and Seed Data
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Optionally add a menu item for the Settings package and insert example dummy data into the database.
```bash
# [optional] add a menu item for it in resources/views/vendor/backpack/ui/inc/menu_items.blade.php:
php artisan backpack:add-menu-content ""
# [optional] insert some example dummy data to the database
php artisan db:seed --class="Backpack\Settings\database\seeds\SettingsTableSeeder"
```
--------------------------------
### Create Operation Trait Example
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
Illustrates the structure of a CreateOperation trait, containing create() and store() actions.
```php
trait CreateOperation
{
public function create()
{
// ...
}
public function store()
{
// ...
}
}
```
--------------------------------
### Install Laravel Charts
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Install the laravel-charts package using Composer. This package provides a unified PHP syntax for multiple charting libraries.
```bash
composer require consoletvs/charts:"6.*"
```
--------------------------------
### TagCrudController Example
Source: https://backpackforlaravel.com/docs/7.x/getting-started-basics
A basic example of a TagCrudController demonstrating how to define CRUD operations, set the model, route, and entity names, and configure fields for list and create operations.
```php
type('text');
CRUD::field('slug')->type('text')->label('URL Segment (slug)');
}
public function setupUpdateOperation()
{
$this->setupCreateOperation();
}
}
```
--------------------------------
### Setup Show Operation - Configure Tab Type
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-show
Change the tab display from the default horizontal to vertical by setting the `tabsType` operation setting. This can be done globally in `config/backpack/operations/show.php` or within the setup function.
```php
$this->crud->setOperationSetting('tabsType', 'vertical')
```
--------------------------------
### Initialize Git Repository and Commit Package Files
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-how-to-create-a-theme
Navigate to the package directory, initialize a Git repository, optionally remove `.gitkeep` files, and commit the initially generated files.
```bash
# go to the package folder (of course - use your names here)
cd packages/vendor-name/package-name
# create a new git repo
git init
# (optional, but recommended)
# by default the skeleton includes folders for most of the stuff you need
# so that it's easier to just drag&drop files there; but you really
# shouldn't have folders that you don't use in your package;
# so an optional but recommended step here would be to
# delete all .gitkeep files, so that you leave the
# empty folders empty; that way, you can still
# drag&drop stuff into them, but Git will
# ignore the empty folders
find . -name ".gitkeep" -print # shows all .gitkeep files, to double-check
find . -name ".gitkeep" -exec rm -rf {} \; # deletes all .gitkeep files
# commit the initially generated files
git add .
git commit -am "generated package code using laravel-packager and the backpack theme-skeleton"
```
--------------------------------
### Define Routes for Moderate Operation
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
Use the setupOperationNameRoutes convention to define GET and POST routes for the moderate operation within your controller.
```php
protected function setupModerateRoutes($segment, $routeName, $controller)
{
Route::get($segment.'/{id}/moderate', [
'as' => $routeName.'.getModerate',
'uses' => $controller.'@getModerateForm',
'operation' => 'moderate',
]);
Route::post($segment.'/{id}/moderate', [
'as' => $routeName.'.postModerate',
'uses' => $controller.'@postModerateForm',
'operation' => 'moderate',
]);
}
```
--------------------------------
### Generated CRUD Operation Trait Example
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
This is an example of a generated operation trait for 'Comment'. It includes route setup, default operation settings, and the method to perform the operation.
```php
$routeName.'.comment',
'uses' => $controller.'@comment',
'operation' => 'comment',
]);
}
/**
* Add the default settings, buttons, etc that this operation needs.
*/
protected function setupCommentDefaults()
{
$this->crud->allowAccess('comment');
$this->crud->operation('comment', function () {
$this->crud->loadDefaultOperationSettingsFromConfig();
});
$this->crud->operation('list', function () {
// $this->crud->addButton('top', 'comment', 'view', 'crud::buttons.comment');
// $this->crud->addButton('line', 'comment', 'view', 'crud::buttons.comment');
});
}
/**
* Show the view for performing the operation.
*
* @return Response
*/
public function comment()
{
$this->crud->hasAccessOrFail('comment');
// prepare the fields you need to show
$this->data['crud'] = $this->crud;
$this->data['title'] = $this->crud->getTitle() ?? 'comment '.$this->crud->entity_name;
// load the view
return view("crud::operations.comment", $this->data);
}
}
```
--------------------------------
### Create Moderate Operation Trait
Source: https://backpackforlaravel.com/docs/7.x/crud-operations
Isolate reusable operation logic into a trait for use across multiple EntityCrudControllers. This example defines routes and default setup for a 'moderate' operation.
```php
$routeName.'.getModerate',
'uses' => $controller.'@getModerateForm',
'operation' => 'moderate',
]);
Route::post($segment.'/{id}/moderate', [
'as' => $routeName.'.postModerate',
'uses' => $controller.'@postModerateForm',
'operation' => 'moderate',
]);
}
protected function setupmoderateDefaults()
{
$this->crud->allowAccess('moderate');
$this->crud->operation('list', function() {
$this->crud->addButtonFromView('line', 'moderate', 'moderate', 'beginning');
});
}
public function getModerateForm($id)
{
$this->crud->hasAccessOrFail('update');
$this->crud->setOperation('Moderate');
// get the info for that entry
$this->data['entry'] = $this->crud->getEntry($id);
$this->data['crud'] = $this->crud;
$this->data['title'] = 'Moderate '.$this->crud->entity_name;
return view('vendor.backpack.crud.moderate', $this->data);
}
public function postModerateForm(Request $request = null)
{
$this->crud->hasAccessOrFail('update');
// TODO: do whatever logic you need here
// ...
// You can use
// - $this->crud
// - $this->crud->getEntry($id)
// - $request
// ...
// show a success message
\Alert::success('Moderation saved for this entry.')->flash();
return \Redirect::to($this->crud->route);
}
}
```
--------------------------------
### Populate the Database and Seed Data
Source: https://backpackforlaravel.com/docs/7.x/demo
Generate the application key, run database migrations, and seed the database with necessary data for the demo.
```bash
php artisan key:generate
php artisan migrate
php artisan db:seed --class="Backpack\Settings\database\seeds\SettingsTableSeeder"
php artisan db:seed
```
--------------------------------
### Registering Eloquent Events in setupCreateOperation
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-create
Use the `creating` event within the `setupCreateOperation` method to perform actions before an entry is created. Ensure the `setupCreateOperation` method is called for these events to register.
```php
public function setupCreateOperation()
{
// ...
Product::creating(function($entry) {
$entry->author_id = backpack_user()->id;
});
}
```
--------------------------------
### Manual Auth Routes Setup (Laravel Default)
Source: https://backpackforlaravel.com/docs/7.x/base-how-to
If you disable Backpack's default auth routes, you can manually register them to point to your Auth controllers. This example shows how to use Laravel's default routes.
```php
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix')], function () {
Route::auth();
Route::get('logout', 'Auth\LoginController@logout');
});
```
--------------------------------
### Use Widget from Package with Fluent Syntax
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Demonstrates adding a widget from a package using the fluent `Widget::add()->from()` syntax, specifying the package's view namespace.
```php
// using the fluent syntax, use the 'from' alias
Widget::add($widget_definition_array)->from('package::widgets');
```
--------------------------------
### Install Revise Operation Package
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-revisions
Install the Backpack Revise Operation package using Composer. This command also installs the venturecraft/revisionable dependency if it's not already present.
```bash
composer require backpack/revise-operation
```
--------------------------------
### Example Theme View Fallback Configuration
Source: https://backpackforlaravel.com/docs/7.x/base-themes
Illustrates a custom theme view namespace with a fallback to a specific Backpack theme. Backpack searches for views in the specified order.
```php
'view_namespace' => 'admin.theme-custom.',
'view_namespace_fallback' => 'backpack.theme-tabler::',
```
--------------------------------
### Use Widget from Package by Specifying View Namespace
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Shows how to add a widget from a package by explicitly defining the `viewNamespace` in the widget definition array.
```php
// using the widget definition array, specify its 'viewNamespace'
Widget::add([
'type' => 'card',
'viewNamespace' => 'package::widgets',
'wrapper' => ['class' => 'col-sm-6 col-md-4'],
'class' => 'card text-white bg-primary text-center',
'content' => [
// 'header' => 'Another card title',
'body' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non mi nec orci euismod venenatis. Integer quis sapien et diam facilisis facilisis ultricies quis justo. Phasellus sem turpis, ornare quis aliquet ut, volutpat et lectus. Aliquam a egestas elit.',
],
]);
```
--------------------------------
### Clone the Demo Repository
Source: https://backpackforlaravel.com/docs/7.x/demo
Clone the official Backpack demo repository to your local machine.
```bash
git clone https://github.com/Laravel-Backpack/demo.git backpack-demo
```
--------------------------------
### Setup Show Operation - Display Columns in Tabs
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-show
Organize columns into tabs by adding the `tab` attribute. This requires the `show.tabsEnabled` operation setting to be true. Supports both array and fluent syntax for column definition.
```php
public function setupShowOperation()
{
// using the array syntax
CRUD::column([
'name' => 'name',
'tab' => 'General',
]);
// or using the fluent syntax
CRUD::column('description')->tab('Another tab');
}
```
--------------------------------
### Adding Livewire Widget to Page
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Example of how to add the 'hello-world' Livewire widget to a page using the Widget::add() facade. It specifies the content, parameters, and wrapper class.
```php
// add the widget to the page
Widget::add()->type('livewire')->content('hello-world')->parameters(['name' => 'John Doe'])->wrapperClass('col-md-12 text-center');
```
--------------------------------
### Install Backpack File Manager
Source: https://backpackforlaravel.com/docs/7.x/crud-how-to
Install the backpack/filemanager package to integrate elFinder into your Laravel project. This requires composer and artisan commands.
```bash
# require the package
composer require backpack/filemanager
# then run the installation process
php artisan backpack:filemanager:install
```
--------------------------------
### Run Custom Views in setupListOperation
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-list-entries
Call runCustomViews() in your setupListOperation() method to activate custom views. Optionally, customize view titles by passing an array.
```php
$this->runCustomViews();
```
```php
$this->runCustomViews([
'setupLast12MonthsView' => __('Last 12 months'),
'setupLast6MonthsView' => __('Last 6 months'),
]);
```
--------------------------------
### Setup MorphMany Relationship Subform
Source: https://backpackforlaravel.com/docs/7.x/crud-how-to
Configure a subform for a morphMany relationship, similar to a HasMany creatable setup, to manage multiple related entries.
```php
// inside PostCrudController::setupCreateOperation() and inside VideoCrudController::setupCreateOperation()
CRUD::field('comments')->subfields([['name' => 'comment_text']]); //note comment_text is a text field in the comment table.
```
--------------------------------
### Install Backpack CRUD Package
Source: https://backpackforlaravel.com/docs/7.x/installation
Use Composer to require the Backpack CRUD package for version 7.0. This is the first step in installing Backpack.
```bash
composer require backpack/crud:"^7.0"
```
--------------------------------
### Setup Pivot Fields in Backpack CRUD Controller
Source: https://backpackforlaravel.com/docs/7.x/crud-how-to
Configure the pivot fields within your CRUD controller's setup method to display them in the form.
```php
// inside UserCrudController::setupCreateOperation()
CRUD::field('roles')->subfields([
['name' => 'notes', 'type' => 'textarea'],
['name' => 'some_other_field']
]);
```
--------------------------------
### Add Custom Widgets to Reorder Operation
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-reorder
Define custom widgets within the setupReorderOperation() function to display content in the 'before_content' section. This example shows how to add widgets using fluent syntax and array definitions, including a 'div' widget to arrange other widgets in a row. It also demonstrates adding external JavaScript and CSS files.
```php
public function setupReorderOperation()
{
// dynamic data to render in the following widget
$userCount = \App\Models\User::count();
//add div row using 'div' widget and make other widgets inside it to be in a row
Widget::add()->to('before_content')->type('div')->class('row')->content([
//widget made using fluent syntax
Widget::make()
->type('progress')
->class('card border-0 text-white bg-primary')
->progressClass('progress-bar')
->value($userCount)
->description('Registered users.')
->progress(100 * (int)$userCount / 1000)
->hint(1000 - $userCount . ' more until next milestone.'),
//widget made using the array definition
Widget::make(
[
'type' => 'card',
'class' => 'card bg-dark text-white',
'wrapper' => ['class' => 'col-sm-3 col-md-3'],
'content' => [
'header' => 'Example Widget',
'body' => 'Widget placed at "before_content" secion in same row',
]
]
),
]);
//you can also add Script & CSS to your page using 'script' & 'style' widget
Widget::add()->type('script')->stack('after_scripts')->content('https://code.jquery.com/ui/1.12.0/jquery-ui.min.js');
Widget::add()->type('style')->stack('after_styles')->content('https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.0.0-beta.58/dist/themes/light.css');
}
```
--------------------------------
### Custom Route Configuration Options
Source: https://backpackforlaravel.com/docs/7.x/base-how-to
Configuration options in config/backpack/base.php for customizing routing, including the route prefix, auth routes setup, and dashboard routes setup.
```php
/*
|--------------------------------------------------------------------------
| Routing
|--------------------------------------------------------------------------
*/
// The prefix used in all base routes (the 'admin' in admin/dashboard)
'route_prefix' => 'admin',
// Set this to false if you would like to use your own AuthController and PasswordController
// (you then need to setup your auth routes manually in your routes.php file)
'setup_auth_routes' => true,
// Set this to false if you would like to skip adding the dashboard routes
// (you then need to overwrite the login route on your AuthController)
'setup_dashboard_routes' => true,
```
--------------------------------
### Advanced Dataform Configuration
Source: https://backpackforlaravel.com/docs/7.x/base-components
Configure the dataform for update operations with a specific entry and custom setup logic. This allows for modifications to the operation setup, such as removing columns.
```blade
```
--------------------------------
### Install TinyMCE Field Addon
Source: https://backpackforlaravel.com/docs/7.x/upgrade-guide
If you were using the 'tinymce' field or column (previously in the PRO package), install the new open-source addon by running this composer command.
```bash
composer require backpack/tinymce-field
```
--------------------------------
### Install CKEditor Field Addon
Source: https://backpackforlaravel.com/docs/7.x/upgrade-guide
If you were using the 'ckeditor' field or column (previously in the PRO package), install the new open-source addon by running this composer command.
```bash
composer require backpack/ckeditor-field
```
--------------------------------
### Initialize Git Repository in Package
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-using-the-addon-skeleton
Initializes a new Git repository within the generated package directory and commits the initial files.
```bash
# go to the package folder (of course - use your names here)
cd packages/vendor-name/package-name
# create a new git repo
git init
# (optional, but recommended)
# by default the skeleton includes folders for most of the stuff you need
# so that it's easier to just drag&drop files there; but you really
# shouldn't have folders that you don't use in your package;
# so an optional but recommended step here would be to
# delete all .gitkeep files, so that you leave the
# empty folders empty; that way, you can still
# drag&drop stuff into them, but Git will
# ignore the empty folders
find . -name ".gitkeep" -print # shows all .gitkeep files, to double-check
find . -name ".gitkeep" -exec rm -rf {} \;
# commit the initially generated files
git add .
git commit -am "generated package code using laravel-packager and the backpack addon-skeleton"
```
--------------------------------
### Configure Daily Log Files
Source: https://backpackforlaravel.com/docs/7.x/install-optionals
Ensure your application is configured to create a new log file for each day by setting APP_LOG=daily in your .ENV file or 'log' => env('APP_LOG', 'daily') in config/app.php.
```dotenv
APP_LOG=daily
```
--------------------------------
### Configure Composer for Private Repositories
Source: https://backpackforlaravel.com/docs/7.x/demo
Set up Composer to authenticate with the private Backpack repository using your token. Replace placeholders with your actual token credentials.
```bash
composer config http-basic.backpackforlaravel.com [your-token-username] [your-token-password]
```
--------------------------------
### Create Theme Directory
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-how-to-create-a-theme
Create a directory for your theme files within resources/views. This directory will house all your theme's assets and views.
```bash
mkdir resources/views/my-cool-theme
```
--------------------------------
### Add Custom Widgets to Create Operation
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-create
Demonstrates how to add custom widgets, including dynamic data widgets and array-defined widgets, to the 'before_content' section of the create operation. Also shows how to add external scripts and styles.
```php
public function setupCreateOperation()
{
// dynamic data to render in the following widget
$userCount = \App\Models\User::count();
//add div row using 'div' widget and make other widgets inside it to be in a row
Widget::add()->to('before_content')->type('div')->class('row')->content([
//widget made using fluent syntax
Widget::make()
->type('progress')
->class('card border-0 text-white bg-primary')
->progressClass('progress-bar')
->value($userCount)
->description('Registered users.')
->progress(100 * (int)$userCount / 1000)
->hint(1000 - $userCount . ' more until next milestone.'),
//widget made using the array definition
Widget::make(
[
'type' => 'card',
'class' => 'card bg-dark text-white',
'wrapper' => ['class' => 'col-sm-3 col-md-3'],
'content' => [
'header' => 'Example Widget',
'body' => 'Widget placed at "before_content" secion in same row',
]
]
),
]);
//you can also add Script & CSS to your page using 'script' & 'style' widget
Widget::add()->type('script')->stack('after_scripts')->content('https://code.jquery.com/ui/1.12.0/jquery-ui.min.js');
Widget::add()->type('style')->stack('after_styles')->content('https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.0.0-beta.58/dist/themes/light.css');
}
```
--------------------------------
### Configuring File Uploaders
Source: https://backpackforlaravel.com/docs/7.x/crud-uploaders
Customize file storage location and disk using options within `withFiles()`. Ensure the storage disk is correctly configured in `config/filesystems.php`.
```php
CRUD::field('avatar')
->type('upload')
->withFiles([
'disk' => 'public', // the disk where file will be stored
'path' => 'uploads', // the path inside the disk where file will be stored
]);
```
--------------------------------
### Get Registered Filters
Source: https://backpackforlaravel.com/docs/7.x/crud-api
Retrieves all filters that have been registered for the list view.
```php
$this->crud->filters();
```
--------------------------------
### Create Tag Table Migration
Source: https://backpackforlaravel.com/docs/7.x/getting-started-basics
Generate a migration file for the 'tags' table with 'name' and 'slug' columns, then run the migration.
```bash
# STEP 1. create a migration
php artisan make:migration:schema create_tags_table --model=0 --schema="name:string:unique,slug:string:unique"
php artisan migrate
```
--------------------------------
### Create and Run Revisions Table Migration
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-revisions
Copy the revisionable migration file to your project's migrations directory and then run the artisan migrate command to create the necessary database table for storing revisions.
```bash
cp vendor/venturecraft/revisionable/src/migrations/2013_04_09_062329_create_revisions_table.php database/migrations/ && php artisan migrate
```
--------------------------------
### Generate New Package with Backpack Skeleton
Source: https://backpackforlaravel.com/docs/7.x/add-ons-tutorial-using-the-addon-skeleton
Creates a new package using the Backpack addon-skeleton. This command prompts for package details and sets up the initial structure.
```bash
php artisan packager:new --i --skeleton="https://github.com/Laravel-Backpack/addon-skeleton/archive/master.zip"
```
--------------------------------
### Register Moderate Route
Source: https://backpackforlaravel.com/docs/7.x/crud-buttons
Registers a GET route for moderating a user, pointing to the moderate method in UserCrudController.
```php
Route::get('user/{id}/moderate', 'UserCrudController@moderate');
```
--------------------------------
### Publish Mobile and Favicon Headers and Assets
Source: https://backpackforlaravel.com/docs/7.x/base-how-to
Run this Artisan command to publish necessary files for mobile bookmarks and favicons. Customize these files to match your branding. Existing files will not be overwritten.
```bash
php artisan backpack:publish-header-metas
```
--------------------------------
### Field Definition (Fluent Syntax)
Source: https://backpackforlaravel.com/docs/7.x/crud-fluent-syntax
An example of defining a field using the Fluent API's method chaining.
```php
$this->crud->field('price')
->type('number')
->label('Price')
->prefix('$')
->suffix('.00');
```
--------------------------------
### Get current action context
Source: https://backpackforlaravel.com/docs/7.x/crud-fields-javascript-api
Access the `crud.action` property to determine if the current page is for 'create' or 'edit' operations.
```javascript
crud.action
```
--------------------------------
### Define 'week' Column Type
Source: https://backpackforlaravel.com/docs/7.x/crud-columns
Defines a column to display the ISO-8601 week number. Weeks start on Monday.
```php
[
'name' => 'week',
'type' => 'week',
'label' => 'Week',
]
```
--------------------------------
### Add Moderate Button to Setup
Source: https://backpackforlaravel.com/docs/7.x/crud-buttons
Adds the custom 'moderate' button to the 'line' stack at the 'beginning' of the CRUD list operation.
```php
CRUD::addButtonFromView('line', 'moderate', 'moderate', 'beginning');
```
--------------------------------
### Publish List View
Source: https://backpackforlaravel.com/docs/7.x/crud-operation-list-entries
Use the backpack:publish command to copy the default list.blade.php file to your resources/views/vendor/backpack/crud directory for customization.
```bash
php artisan backpack:publish crud/list
```
--------------------------------
### Title, Heading, Subheading
Source: https://backpackforlaravel.com/docs/7.x/crud-api
Set and get the title, heading, and subheading for CRUD operations, allowing for customizable display text.
```APIDOC
## Title, Heading, Subheading
### Description
Set and retrieve the title, heading, and subheading for specific CRUD operations.
### Methods
- `getTitle(string $operation)`: Get the Title for a given operation (e.g., 'create').
- `getHeading(string $operation)`: Get the Heading for a given operation.
- `getSubheading(string $operation)`: Get the Subheading for a given operation.
- `setTitle(string $title, string $operation)`: Set the Title for a given operation.
- `setHeading(string $heading, string $operation)`: Set the Heading for a given operation.
- `setSubheading(string $subheading, string $operation)`: Set the Subheading for a given operation.
### Example Usage
```php
// Set title, heading, and subheading for the 'create' operation
$this->crud->setTitle('Add New Example', 'create');
$this->crud->setHeading('Create Example', 'create');
$this->crud->setSubheading('Form to add a new example record', 'create');
// Get the title for the 'create' operation
$title = $this->crud->getTitle('create');
```
```
--------------------------------
### Get CRUD Title
Source: https://backpackforlaravel.com/docs/7.x/crud-api
Retrieve the title for a specific CRUD action (e.g., 'create', 'update'). Titles are displayed to the user.
```php
$this->crud->getTitle('create');
```
--------------------------------
### Progress Widget Configuration
Source: https://backpackforlaravel.com/docs/7.x/base-widgets
Configure a progress widget to display a colorful card indicating progress towards a goal. Customize class names for different appearances and use helper classes for alignment and text color.
```php
[
'type' => 'progress',
'class' => 'card text-white bg-primary mb-2',
'value' => '11.456',
'description' => 'Registered users.',
'progress' => 57, // integer
'hint' => '8544 more until next milestone.',
]
```
--------------------------------
### Make a button the first
Source: https://backpackforlaravel.com/docs/7.x/crud-fluent-syntax
Use the makeFirst() method to set the current button as the first button for the operation.
```php
CRUD::button('name')->makeFirst();
```