how to Generate CRUD in Laravel
Tags: laravel
Published: 2021-03-15 10:07:27

Recently I was working with an CRM System where I need to contain long forms with many many fields. So, to manipulate those forms using the classic ways of creating the forms manually is a long-term process.
So, avoid this long-lasting process and to make development easy I decide to use a crud generator to generate from field easily. 
For this purpose, I decide to use a widely used package which is appzcoder/crud-generator.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c59iefcnlhtjeas3vngz.png)
For that the procedure I was done 
Installation:
For installation appzcoder/crud-generator i was type 
composer require appzcoder/crud-generator --dev on my terminal
After that, publish its assets using the vendor:publish Artisan command.
php artisan vendor:publish --provider="Appzcoder\CrudGenerator\CrudGeneratorServiceProvider"

after the execute this command the package created a configuration file in 
config/crudgenerator.php and some other files in resources/crud-generator. 

Then I need to modifi config/crudgenerator.php file

Whay I need to modifi curdgenerator.php ?
Basically the curd generator uses the default Laravel layout but i need to update to be sited the current theme so I was modifi like bellow 


.....
return [
   ...
    'custom_template' => true,
   ....
];

 Then i was modifi all stub crud file s I need. The stub file is located within  resources/crud-generator/views/html/

Generating CRUD View:

Then I was run below command in terminal to generate the views:
php artisan crud:view users --fields="name#string; email#string; position_title#string; phone#string; image#string; parent_id#integer" --view-path="pages" --route-group=admin --form-helper=html --validations="name#required; email#required|email|unique:users,email; password#required"

This command will create the views of (Create, Read, Update, Delete) of the users table in resources/views/pages folder.
 
create the Users controller using the crud:
php artisan crud:controller UsersController --crud-name=users --model-name=User --view-path="pages" --route-group=admin

This command create a resource controller similar to laravel native command instead it will populate it with code ready. Everything is working fine but i decide modifi some code.
 the following modifications to the below files:
The file location is: app/Http/Controllers/UsersController.php

	<?php
 
namespace App\Http\Controllers;
 
use App\Helpers\MailerFactory;
use App\Http\Requests;
 
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
 
class UsersController extends Controller
{
    protected $mailer;
 
    public function __construct(MailerFactory $mailer)
    {
        $this->middleware('admin', ['except' => ['getProfile', 'getEditProfile', 'postEditProfile']]);
 
        $this->mailer = $mailer;
    }
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $keyword = $request->get('search');
 
        $perPage = 25;
 
        if (!empty($keyword)) {
            $users = User::where('name', 'like', "%$keyword%")->orWhere('email', 'like', "%$keyword%")->paginate($perPage);
        } else {
            $users = User::latest()->paginate($perPage);
        }
 
        return view('pages.users.index', compact('users'));
    }
 
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $parents = User::all();
 
        return view('pages.users.create', compact('parents'));
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        $this->validate($request, [
 'name' => 'required',
 'email' => 'required|email|unique:users,email',
 'password' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif'
 ]);
 
        $requestData = $request->except(['is_profile', '_token']);
 
        $requestData['password'] = bcrypt($requestData['password']);
 
        $requestData['is_active'] = isset($requestData['is_active'])?1:0;
 
        if ($request->hasFile('image')) {
 
            checkDirectory("users");
 
            $requestData['image'] = uploadFile($request, 'image', public_path('uploads/users'));
        }
 
        if(($count = User::all()->count()) && $count == 0) {
 
            $requestData['is_admin'] = 1;
        }
 
        User::create($requestData);
 
        return redirect('admin/users')->with('flash_message', 'User added!');
    }
 
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $user = User::findOrFail($id);
 
        return view('pages.users.show', compact('user'));
    }
 
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $user = User::findOrFail($id);
 
        return view('pages.users.edit', compact('user'));
    }
 
    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
 'name' => 'required',
 'email' => 'required|email|unique:users,email,' . $id,
            'image' => 'image|mimes:jpeg,png,jpg,gif'
 ]);
 
        $requestData = $request->except(['_token']);
 
        if ($request->hasFile('image')) {
            checkDirectory("users");
            $requestData['image'] = uploadFile($request, 'image', public_path('uploads/users'));
        }
 
        $user = User::findOrFail($id);
 
        $old_is_active = $user->is_active;
 
        if($user->is_admin == 0) {
            $requestData['is_active'] = isset($requestData['is_active']) ? 1 : 0;
        }
 
        $user->update($requestData);
 
 
        // send notification email
        if($user->is_admin == 0 && getSetting("enable_email_notification") == 1 && $requestData['is_active'] != $old_is_active) {
 
            if($requestData['is_active'] == 1) {
                $subject = "Your mini crm account have been activated";
            } else {
                $subject = "Your mini crm account have been deactivated";
            }
 
            $this->mailer->sendActivateBannedEmail($subject, $user);
        }
 
        return redirect('admin/users')->with('flash_message', 'User updated!');
    }
 
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        User::destroy($id);
 
        return redirect('admin/users')->with('flash_message', 'User deleted!');
    }
 
 
    /**
     * show user profile
     *
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getProfile()
    {
        $user = User::findOrFail(Auth::user()->id);
 
        return view('pages.users.profile.view', compact('user'));
    }
 
    public function getEditProfile()
    {
        $user = User::findOrFail(Auth::user()->id);
 
        return view('pages.users.profile.edit', compact('user'));
    }
 
    public function postEditProfile(Request $request)
    {
        $id = Auth::user()->id;
 
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $id,
            'image' => 'image|mimes:jpeg,png,jpg,gif'
        ]);
 
        $requestData = $request->except(['_token']);
 
        if ($request->hasFile('image')) {
            checkDirectory("users");
            $requestData['image'] = uploadFile($request, 'image', public_path('uploads/users'));
        }
 
        if(!empty($requestData['password'])) {
 
            $requestData['password'] = bcrypt($requestData['password']);
        } else {
            unset($requestData['password']);
        }
 
        $user = User::findOrFail($id);
 
        $user->update($requestData);
 
        return redirect('admin/my-profile')->with('flash_message', 'Profile updated!');
    }
}
Finally, crud generation successfully done
.
that's it.
.
Happy Coding.
osman forhad
Mobile & Web Application Developer💻