online software programming courses

Laravel backend common functions

Laravel Admin Panel commonly used tips and functions

Creating a Controller

Say you want to create a controller for backend to show the user data, then you need to run the below command

php artisan admin:make UserController --model=App\\Models\\User

The above command will create a user controller  as UserController in Admin/Controllers directory.

Then you need to add the controller resources in your Admin/routes.php file like below

<?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');

     //we added this one
     $router->resource('users', UsersController::class);

});

View the Data

Then if you open up your UsersController.php you will see the code

<?php

namespace App\Admin\Controllers;

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

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

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

        $grid->column('id', __('Id'));
        $grid->column('name', __('Name'));
        $grid->column('email', __('Email'));
        $grid->column('img', __('Thumbnail Photo'))->image('',60,60);
        //$grid->column('email_verified_at', __('Email verified at'));
        //$grid->column('password', __('Password'));
        //$grid->column('remember_token', __('Remember token'));
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));
        $grid->column('status', __('Status'));
        $grid->column('description', __('Description'));
        $grid->column('due_date', __('Due date'));

        return $grid;
    }

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

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $show->field('email', __('Email'));
        $show->field('img', __('Img'))->image();
        //$show->field('email_verified_at', __('Email verified at'));
        //$show->field('password', __('Password'));
       // $show->field('remember_token', __('Remember token'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('status', __('Status'));
        $show->field('description', __('Description'));
        $show->field('due_date', __('Due date'));

        return $show;
    }

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

        $form->text('name', __('Name'));
        $form->email('email', __('Email'));
       // $form->datetime('email_verified_at', __('Email verified at'))->default(date('Y-m-d H:i:s'));
       // $form->password('password', __('Password'));
        //$form->text('remember_token', __('Remember token'));
         $form->image('img', __('Img'))->uniqueName();
        $form->switch('status', __('Status'));
        $form->text('description', __('Description'));
        $form->datetime('due_date', __('Due date'))->default(date('Y-m-d H:i:s'));

        return $form;
    }
}

Here the grid() method shows all the record from the database from for the User and the detail() is for editing each of them. And form() method for creating a new record to the database for UserController.

Creating a Thumbnail

If you want to show a thumbnail like below in your backend

then in your form() method a line like below

 $form->image('img', __('Img'))->uniqueName();

After that in your database you need to create a column as img. You shoule be good to go. If you encounter error follow the link https://www.dbestech.com/tutorials/laravel-admin-panel-config-problems-and-solutions

In general, the above function would create a unique name for each thumbnail before uploading to the upload folder. It does so to avoid the name confliction with other images.

If you want to upload the image with customize name, you can do like below

 $form->image('img', __('Thumbnail'))->required()->name(function($file) {
        $type = explode('.', $file->getClientOriginalName());
        return request('name') . $type[0].'_' . time().'.'.$type[1];
 });

The above callback function takes the original file name(that means whatever you upload the name) and then split it. It inserts PHP time() funciton to tag a time to the cuztomize image name. If you want you may not use time() funciton.

Date Format

If you have the date shown like below with 0000000Z

Then you need to add a property in your corresonding model. In our case it's UserController model. We will add the below line

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

class UserController extends Model
{
    use DefaultDatetimeFormat;
};

//or like below.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;
 
class UserController extends Model
{
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
 
}

Showing options

If you want to show options in your backend like below

You need to create an eloquent relationship in your model like say "Blog" and those two options would be coming from "Category" model. So in your Blog model you would create a relationship like below

 public function category(){
        return $this->belongsTo(Category::class);
    }

And now in your BlogController you would do like below in your form() method

    protected function form()
    {
        $form = new Form(new Blog());

        $cat= new Category();
       //category_id should be saved in blogs table
        $form->select('category_id', __('Select topic'))->options($cat::all()->pluck('name', 'id'))->required();
        
        $form->text('description', __('Detail'));

        return $form;
    }

Do remember that, you need to save the category_id in your blogs table in the database. 

Creating Boolean Switch

If you model has a boolean property and you want to toggle the values in your backend controller page, then in the do like this form() method

$form->switch('status', __('Status'));

in the detail() method

$show->field('status', __('Status'));

and in the grid method

$grid->column('status', __('Status'));

So here 'status's is a boolean field in model. If status is an integer field you need convert that to boolean. And you will see like this

Change the order

Just add the below code. It will show all the record from the database for the model from descending order.

 $grid->model()->orderBy('created_at','desc');

Hide the filter button

In general you have a filter button in your records. With the filter button you can do filter id. 

But if you want to hide it, add the below code in your grid method

$grid->disableFilter();

And you will see it's gone.

Replace value in the column

If you want to replace some content in your laravel admin panel column do like this

$grid->column('cost')->replace([0 => '-']);

If the column cost value is 0, then we will replace it with -.

If say you you like below

$grid->column('last_name')->replace([null => 'No name found']);

If user did not put last name, then we will replace the null value with 'No name found'. 

See from the above picture, the last row, there was no last name metioned, but we are able to replace the null value.