Build Laravel Admin Panel - Best Backend

Created At: 2021-11-26 03:12:29 Updated At: 2023-10-25 03:05:57

Build Laravel Admin Panel - Best Backend. Here we will see how we can easily do CRUD oeperation with this admin package. This admin package as Laravel backend has been used in many tutorials and thousands of students have been benefited with this and this is free to use. Check out from the link that used this admin panel for advanced e-commerce systems.

Food delivery app with Laravel Admin Panel

Course selling app with Laravel Admin Panel

Here is a free of laravel according to youtube tutorial to install

Install Laravel

First go ahead install laravel in your machine. You can use the below command to install it in your project. So it will install laravel. 

composer create-project laravel/laravel 

Then you can use the serve command to start the app if you are localhost. If you are on server, then you need to run the commands here. 

Laravel artisan commands

php artisan serve

But if you are installing in your server, you might need to create virtual host(only for dedicated server). At the same time make sure that you configured your database and .env file. Otherwise admin panel wont' work.

 

Install Laravel Admin

After installing Laravel, it's time to install laravel-admin package. You can get lot more information here in this link

https://laravel-admin.org/docs/en/installation

You can install laravel-admin panel using composer. Type in the below command

composer require encore/laravel-admin:1.*

It will download the latest version of Laravel Admin Panel in your project folder. After that you need to publish it using the below command

php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider"

After that you will have to run the below command to install and activate it

php artisan admin:install

With the above command we are done with most basic laravel admin panel.

Open http://localhost/admin/ in browser,use username admin and password admin to login. If you are on server, change local host with your domain name.

Config File

After that we will have some generated files. One of the most important file is config/admin.php

Admin Files

Most of the php files would be under in your app/Admin folder. The PHP files in this folder are to help you build robust admin panel.

Look at the structure of the app/Admin folder.

In the Controllers folder we will put all of our generated controllers for our backend. We will see it soon

routes.php holds the routes for the backend. and bootstrap.php is used to remove some builtin features or add some features.

Now will go ahead and customize our backend. We will a backend where we would be able to post articles, update articles, delete them. We would be able to create and remove categories. At the end we will show the result in row and column grid. 

Customized Backend

First we will run the below two commands to generate two models. One for article and another one for article type.

php artisan make:model Article
php artisan make:model ArticleType

Then in your app/Models/ you will see two php files like below

app models

For these two models now we will create two controllers. Now we will run the below commands

php artisan admin:make ArticleController --model='App\Models\Article'

php artisan admin:make ArticleTypeController --model='App\Models\ArticleType'

With these commands now our app/Admin/Controllers folder will look like below

app admin controllers

If the above command did not work, you may try the below one 

php artisan admin:make ArticleController --model=App\\Models\\Article

php artisan admin:make ArticleTypeController --model=App\\Models\\ArticleType

Instead of single quotes you may also use double slashes.

Adding Routes

Now in our app/Admin/routes.php file we need to mention the resources we created.

<?php

use Illuminate\Routing\Router;

Admin::routes();

Route::group([
    'prefix'        => config('admin.route.prefix'),
    'namespace'     => config('admin.route.namespace'),
    'middleware'    => config('admin.route.middleware'),
    'as'            => config('admin.route.prefix') . '.',
], function (Router $router) {

    $router->get('/', 'HomeController@index')->name('home');
    $router->resource('articles', ArticleController::class);
    $router->resource('article-types', ArticleTypeController::class);

});

Now your routes.php should look like the above code.

 

Database Tables

Now look at our database tables. We want to create two tables. One is articles and the other one is article_types. They will have the below fields. 

For articles table

and for article_types

So first we need to create two migration files. We will run the below commands to generate migration files for articles and article types table

php artisan make:migration create_articles_table

php artisan make:migration create_article_types_table

 

So now we will go ahead and write these fields in our migration files. First for articles

    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->tinyInteger("type_id");
            $table->string("sub_title")->nullable();
            $table->text("description");
            $table->tinyInteger("released")->default(0);
            $table->string("thumbnail")->nullable();
            $table->timestamps();
        });
    }

 

Now we will do the same for article types migration files

    public function up()
    {
        Schema::create('article_types', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->integer("parent_id");
            $table->integer("order");
            $table->timestamps();
        });
    }

After that we will run the migration with the below command

php artisan migrate

 

See the Controllers

After that we will head hover to our app/Admin/Controllers/ArticleTypeController.php and see the file.

<?php

namespace App\Admin\Controllers;

use App\Models\ArticleType;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class ArticleTypeController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'ArticleType';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ArticleType());



        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ArticleType::findOrFail($id));



        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ArticleType());



        return $form;
    }
}

 

After that we will head hover to our app/Admin/Controllers/ArticleController.php and see the file.

<?php

namespace App\Admin\Controllers;

use App\Models\Article;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class ArticleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Article';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Article());



        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Article::findOrFail($id));



        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Article());



        return $form;
    }
}

Soon we will change the grid(), detail() and form() method of this files. They are the core functions for our backend customization. 

Each of them takes models as we create object from them. 

grid() method is responsible for showing the data in row and column pattern. As you can see, it takes a model in its constructor.

form() method is responsible for creating forms and submitting data to the database. It also takes a model.

detail() method is responsible for showing the data without editing format.

 

Backend Login

Now we will head over to the backend login page. Type in your domain name like below with

http://localhost/admin

and now you will see a login page like below

Type in admin name and password. In this case they are admin respectively. and you will see the welcome page like below

 

Form for Article Types

Anyway, now we will head over the ArticleTypeController.php, and then we will put the below code in the form() method

    protected function form()
    {
        $form = new Form(new ArticleType());
        $form->select('parent_id', __("Category"))->options((new ArticleType())::selectOptions());
        $form->text('title', __('Name'));
        $form->number('order', __("Order"));
        return $form;
    }

 

Tree Model for Types

then we will delete the grid method and type in the below code with the index() method

    public function index(Content $content)
    {
        $tree = new Tree(new ArticleType);
        return $content
            ->header('Article Type')
            ->body($tree);
    }

And at the top of the ArticleTypeController.php file we need to import the namespace

use App\Models\ArticleType;
use Encore\Admin\Layout\Content;
use Encore\Admin\Tree;

We also need to import namespace for ModelTree in ArticleType.php file. Now the file would look like below

<?php
namespace App\Models;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class ArticleType extends Model
{
    //It changes the default time format
    use DefaultDatetimeFormat;
    use ModelTree;

    protected $table="article_types";
}

 

Form for Article

Now we will work on ArticleController.php file we will change the form() method first, we will put the below code there.

    protected function form()
    {
        $form = new Form(new Article());
        $form->select('type_id', "Select")->options((new ArticleType())::selectOptions());
        $form->text("title")->placeholder("Type in the article title");
        $form->text("sub_title")->placeholder("Type in the article sub title");
        $form->image('thumbnail', __('Thumbnail'))->name(function($file) {
            
          $type = explode('.', $file->getClientOriginalName());
          return request('name') . $type[0].'_' . time().'.'.$type[1];
          
        })->removable()->move('/test/');
        $form->UEditor('description', __('Content'));
            //  $form->saving(function (Form $form) {
           
           // dd($form->model()->image_path);
         //   if($form->model()->image_path){
        //    $ex = explode('.', $form->model()->image_path);
        
          // if($ex[1]!="png"){
               
               //admin_toastr("No way", 'warning');
             //  //return redirect('admin/articles/'.$form->model()->id.'/edit/');
         //  }
        //    }
        });
        $states = [
            'on'=>['value'=>1, 'text'=>'publish', 'color'=>'success'],
            'off'=>['value'=>0, 'text'=>'draft', 'color'=>'default'],
            ];
            
        $form->switch('published', __('Published'))->states($states);
        return $form;
    }

 

Grid View for The Records

And now we will put the below code for grid() method

    protected function grid()
    {
        $grid = new Grid(new Article());
        $grid->column('title', "Title");
        $grid->column('sub_title', __("Sub Title"));
        $grid->column('article.title', __('Category'));
        $grid->column('published')->bool();
        $grid->column('description', __('Content'))->display(function($val){
           return substr($val, 0, 300); 
        });
        
        $grid->column('image_path', __('Thumbnail'))->image('','100', '100')->display(function($val){
            if(empty($val)){
                return "No Thumbnal";
            }
            return $val;
        });
        $grid->model()->orderBy('created_at','desc');
        $grid->filter(function($filter){
           $filter->disableIdFilter();
           $filter->like('title', __('Title'));
           $filter->like('article.title', __('Category'));
        });
        return $grid;
    }

of course at the top, we need to import the models.

use App\Models\ArticleType;
use App\Models\Article;

 

Install Text Editor

In the ArticleController.php file we need to use an editor. You can find the editor installation guide here

install text editor for laravel admin

Comment

Add Reviews