Laravel 5 CRUD tutorial with example

Laravel 5 CRUD tutorial In this tutorial We will cover Laravel Listing, create, update, delete the basic application functionality. All Laravel application must have Larave CRUD tutorial functionality.  I will teach you how to create a Laravel CRUD step by step. This tutorial is useful for Laravel beginner. Because In this tutorial I will cover all basic concept of Laravel for starting an application.

There are many Laravel CRUD generator tutorial but it is not meaning for the beginners. So, For the Beginners user, I am creating this Laravel CRUD Tutorial.

Today, We are going to learn Laravel 5 CRUD tutorial step by step. First of all, We are starting from going to install Laravel application.

Laravel 5 CRUD tutorial

We will follow the steps of creating the Laravel 5 CRUD tutorial

  • Laravel installation
  • Database configuration
  • Integrate AdminLte theme
  • Write the Routes
  • Generate migration files
  • Create the Model
  • Generate Controller
  • Create the Views files

Finally, We are ready with the steps we will follow these steps for creating CRUD Tutorial.

We are going to create the category module for CRUD tutorial. Let's start the CRUD tutorial

1 ) Laravel installation

First of all, We are going to install Laravel using composer by following the command

composer create-project --prefer-dist laravel/laravel laravelhive

Follow this tutorial, For installing Laravel step by step and getting more detail about Laravel Installation.

Finally, We are ready with the Laravel Application. Now, We are going to configure Database.

2 ) Database configuration

After, Creating the  Laravel project open the configuration file .env then change the database configuration like

DB_DATABASE=laravelhive
DB_USERNAME=root
DB_PASSWORD=laravelhive

Next, We are going to run migration for generating Laravel tables

php artisan migrate

If you getting an error by following migration command like 1071 specified key was too long then just follow this tutorial.

Finally, We are ready with the Database configuration. Now, We are going to integrate AdminLTE theme.

3 ) Integrate AdminLte theme

Finally, We are going to integrate AdminLTE theme, But I create the different tutorial for integrating AdminLTE admin theme. Because I want to make this tutorial simple and sort. So, Please follow this tutorial to integrate AdminLTE theme.

Before, Going to the next step make sure the AdminLTE theme is installed properly.

4 ) Write the Routes

Finally, We are ready with the Laravel application with admin theme. Now, First of all, We are going to create the routes for our CRUD tutorial. Let's open the routes/web.php file.

Route::group(['middleware' => 'auth','namespace' => 'Admin','prefix' => 'admin'], function () {
    Route::resource('category','CategoryController');
});

We will create the route group for all admin module URL are located on the same prefix "admin". Also, We have namespace "Admin". So, our Controller files are stored in the Admin folder.

5 ) Generate migration files

Now, Let's create the migration for the category table. We have to create the category table for storing the data in a database. We generate a migration file using artisan command like

php artisan make:migration create_category_table

After, Follow this command the Laravel generate a migration for the category table. Laravel generate migration file at database/migrations You will see the new migration file for a category on migrations folder. Let's open the category migration file and change the code like

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->String('slug');
            $table->text('description');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('category');
    }
}

Finally, We are ready with the migration table. So, Let's run the migration first by the following command

php artisan migrate

The migrate command will create the category table into the database. So, We are ready with the category table. Now, we are going to create the Controller.

6 ) Create the Model

Finally, We are ready with the category table. Now, let's create the model file for the category table by following the command.

php artisan make:model Category

So, Laravel generates Model file inside the app folder. You will find the category model file at app/Category.php let's open the model file then write the code like

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
    protected $table = 'category';
    protected $fillable = ['name', 'slug', 'description'];
    public function getAll( $filters = array() ){
    $categories = $this->select('*');
    foreach( $filters as $key => $value ){
    $categories->where( $value['field'], $value['operation'], $value['value'] );
    }
    return $categories->paginate(10);
    }
}

Finally, We are ready for the Category Model. So, We are going for creating the controller file.

7 ) Generate Controller

We are going to creating the CategoryController file. As per describe on a route. We are using the namespace Admin on the route group. So, We have to create the Controller file inside the Admin folder like App\Http\Controllers\Admin. So, Let's create the Category Controller by the following command

php artisan make:controller Admin\CategoryController

Finally, We are ready with the Category Controller. So, Open the controller and write the code like

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
use View;
use Auth;
class CategoryController extends Controller
{
protected $module_name = "";
    protected $model = "";
    protected $route_path = "category";
protected $view_path = "admin.category";
public function __construct(){
// parent::__construct();
$this->module_name = "Category";
$this->model = new Category;
        View::share('module_name',$this->module_name);
View::share('route_path',$this->route_path);
}
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = array();
        $search = $request->all();
        if( $request->has('search') ){
            $search = $request->get('user_search');
            $where[] = [
                'field' => 'name',
                'value' => '%'.$search.'%',
                'operation' => 'LIKE',
            ];
        }
        $items = $this->model->getAll($where);
        
        return view($this->view_path.'.index',compact('items'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view($this->view_path.'.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'slug' => 'required',
            'description' => 'required',
        ]);
        $inder_data = $request->except(['_token','submit']);
        $inder_data['user_id'] = Auth::user()->id; 
        $this->model->create($inder_data);
        return redirect()->route($this->route_path.'.index')
                        ->with('success',$this->module_name.' created successfully');
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $item = $this->model->find($id);
        return view($this->view_path.'.edit',compact('item'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'slug' => 'required',
            'description' => 'required',
        ]);
        
        $inder_data = $request->except(['_token','_method','submit']);
        $inder_data['user_id'] = Auth::user()->id;
        $this->model->find($id)->update($inder_data);
        return redirect()->route($this->route_path.'.index')
                        ->with('success',$this->module_name.' updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->model->find($id)->delete();
        return redirect()->route($this->route_path.'.index')
                        ->with('success',$this->module_name.' deleted successfully');
    }
}

Finally, We are with the Category Controller. Now, We able to perform the insert, update, delete operation using category controller.

8 ) Create the Views files

Now, We are going for creating the view files. Laravel use blade template for the view file. We can create the user interface using view file. We are going to create three view files for insert, create, update.

  • index.blade.php
  • create.blade.php
  • edit.blade.php

Create all those files inside resources\views\admin\category folder step by step.

First of all, We are going to creating the listing. So, let's open the resources\views\admin\category\index.blade.php file and write the code like

Now, we are going to create the insert category form. So, let's open the resources\views\admin\category\create.blade.php file and write the code like

Now, we are going to create the update category form. So, let's open the resources\views\admin\category\edit.blade.php file and write the code like

We are ready with the Laravel CRUD tutorial. Now we can run the Laravel application and check the CRUD example. Follow the command for running the Laravel application.

php artisan serve

Now, check the category module using this URL.

I hope this Laravel 5 CRUD tutorial is helpful for you. We are creating the reusable Laravel CRUD Code. you can reuse the module by just changing some labels on the Controller file. If you face any issue by following this tutorial please write the comment below.

Tags:

Related Posts: