In this post, we will know the most useful method laravel 5.2. Here we will create a simple Create Read Update Delete (CRUD) application with Laravel 5.2. Following steps help to beginners for implement Create Read Update Delete (CRUD) procedures in Laravel 5.2.
CRUD Operations contains,
- Add a new Form and insert data into the database.
- Get whole data from the database and show on the view page.
- Get and modify existing details and update new data into the database with the help of a primary key and required condition keys.
- Delete data from the database with the help of a primary key or condition keys.
Step 1: Basic Setup
Download the Laravel package and set the basic application requirements like DB connection setting in .env file. Then open the command prompt point to project folder path.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=HOST_NAME DB_PORT=3306 DB_DATABASE=DB_NAME DB_USERNAME=DB_USER DB_PASSWORD=DB_USER_PASSWORD |
Step 2: Create Model & Migration classes
Create a Product model class that interacts with “products” table.
1 |
php artisan make:model Product -m |
Here -m parameter use to create a database migration file at the time of model class creation. Created model class file present in app/ folder. In that file, we need to add some basic details like $fillable, $table and $primaryid for the particular table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'description', ]; } |
Step 3: Created migrations class file present in database/migrations folder. Open the created migrations file and add the required column names to store the basic data from the form with primary key and timestamps. The migrations file name start with some number and table name format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('products'); } } |
Step 4: Controller Creation
The controller is used to handling user request with one class. To handle all the form related request, define a Product Controller by creating a ProductController.php file. This file present in app/Http/Controllers/ folder.
1 |
php artisan make:controller ProductController |
At the starting of the file, we need to use a particular model class to store form data into defined table. It contain index(), show(), add(), insert(), edit(), update(), delete() methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Product; class ProductController extends Controller { public function index(){ //fetch all products data $products = Product::orderBy('id','desc')->get(); //pass products data to view and load list view return view('product.index', ['products' => $products]); } public function show($id){ //fetch product data $product = Product::find($id); //pass products data to view and load list view return view('product.show', ['product' => $product]); } public function add(){ //load form view return view('product.add'); } public function insert(Request $request){ //validate product data $this->validate($request, [ 'name' => 'required', 'description' => 'required' ]); //get product data $productData = $request->all(); //insert product data Product::create($productData); return redirect()->route('product.index')->with('message','Product details added successfully!'); } public function edit($id){ //get product data by id $product = Product::find($id); //load form view return view('product.edit', ['product' => $product]); } public function update($id, Request $request){ //validate product data $this->validate($request, [ 'name' => 'required', 'description' => 'required' ]); //get product data $productData = $request->all(); //update product data Product::find($id)->update($productData); return redirect()->route('product.index')->with('message','Product details updated successfully!'); } public function delete($id){ //update product data Product::find($id)->delete(); return redirect()->route('product.index')->with('message','Product details deleted successfully!'); } } |
Step 5: Route defining
To create the CRUD procedures, we need to set routes, routes are used to handle the view and form submission request process with a controller. A route tells which view want to show to the requested URLs with type. Here get() and post() methods are used define various routes. get() method for showing details from database or controller to view page. post() method for handling form submission data requests to a database. All routes are defined in routes.php it present app/Http/ folder.
1 2 3 4 5 6 7 |
Route::get('/products', array('as'=>'product.index','uses'=>'ProductController@index')); Route::get('/products/add', array('as'=>'product.add','uses'=>'ProductController@add')); Route::post('/products/insert', array('as'=>'product.insert','uses'=>'ProductController@insert')); Route::get('/products/show/{id}', array('as'=>'product.show','uses'=>'ProductController@show')); Route::get('/products/edit/{id}', array('as'=>'product.edit','uses'=>'ProductController@edit')); Route::post('/products/update/{id}', array('as'=>'product.update','uses'=>'ProductController@update')); Route::get('/products/delete/{id}', array('as'=>'product.delete','uses'=>'ProductController@delete')); |
Step 6: Preparing page Layout
Each and every application have a basic layout for entire pages. Here we need to define our app layout with some basic details. Layouts are present in resources/views/layouts/ folder. Here we use basic pageLayout.blade.php as our layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!DOCTYPE html> <html lang="en"> <head> <title>Create Read Update Delete (CRUD) procedures in Laravel 5.2</title> <!-- bootstrap minified css --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- bootstrap minified js --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" > <!-- custom CSS --> <style> h1{font-size:23px; </style> </head> <body> <div class="container"> <br/> <h1 style="text-align: center;">Create Read Update Delete (CRUD) procedures in Laravel 5.2</h1> <br/> <br/> @yield('page_content') </div> </body> </html> |
Step 7: Create Page Views for Form data
All view pages are placed into resources/views/ folder. In that, we need to create one folder with our CRUD handling name like a product, category, state, city etc. Here we create product folder for our product form view pages. Product folder contains index.blade.php, add.blade.php, show.blade.php, edit.blade.php files.
Step 8: Show the All Product List
In this section, all product details list are shown to frontend user for manage the details like Add, View, Update or Remove from Database. Create a file named as index.blade.php as save the data with the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
@extends('layouts.pageLayout') @section('page_content') <div class="row"> <div class="col-lg-12"> <!-- Prodcut list --> @if(!empty($products)) <div class="row"> <div class="col-md-offset-2 col-md-8"> @if(session('message')) <div class="alert alert-success">{{ session('message') }}</div> @endif <div class="pull-left"> <h2>Product List </h2> </div> <div class="pull-right"> <a class="btn btn-success" href="{{ route('product.add') }}"> Add Product</a> </div> <br/> <br/> <table class="table table-striped task-table"> <!-- Table Headings --> <thead> <th width="5%">Sno</th> <th width="40%">Name</th> <th width="">Description</th> <th width="20%">Action</th> </thead> <!-- Table Body --> <tbody> @php( $sno = 1 ) @foreach($products as $product) <tr> <td class="table-text"> <div>{{ $sno++ }}</div> </td> <td class="table-text"> <div>{{$product->name}}</div> </td> <td class="table-text"> <div>{{$product->description}}</div> </td> <td> <a href="{{ route('product.show', $product->id) }}" class="btn btn-success"><i class="fa fa-eye" aria-hidden="true"></i></a> <a href="{{ route('product.edit', $product->id) }}" class="btn btn-warning"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <a href="{{ route('product.delete', $product->id) }}" class="btn btn-danger" onclick="return confirm('Are you sure to delete?')"><i class="fa fa-trash" aria-hidden="true"></i></a> </td> </tr> @endforeach </tbody> </table> </div> </div> @endif </div> </div> @endsection |
Step 9: Create Add new product details
In this section, we need to create New product details form with post data route and save it as add.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
@extends('layouts.pageLayout') @section('page_content') <div class="row"> <div class="col-lg-offset-3 col-lg-6"> @if($errors->any()) <div class="alert alert-danger"> @foreach($errors->all() as $error) <p>{{ $error }}</p> @endforeach() </div> @endif <div class="panel panel-default"> <div class="panel-heading"> Add a New Product </div> <div class="panel-body"> {{ Form::open(array('url' => route('product.insert'), 'method' => 'POST', 'name'=>'fk-input-form', 'id'=>'fs-forms')) }} <div class="form-group"> {{ Form::label('product_name', 'Product Name', ['class' => 'required']) }} {{ Form::text('name', null, ['id'=>'product_name', 'class' => 'form-control', 'placeholder'=>'Product Name'] ) }} </div> <div class="form-group"> {{ Form::label('description', 'Description', ['class' => 'required']) }} {{ Form::textarea('description', null, ['id'=>'description', 'class' => 'form-control', 'placeholder'=>'Description'] ) }} </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <input type="submit" class="btn btn-success" value="Add Product" /> <a href="{{ route('product.index') }}" class="btn btn-primary">Back</a> </div> </div> {{ Form::close() }} </div> </div> </div> </div> @endsection |
Step 10: View the Added Product Details
In this section, we going to show the created or added product details from a database into HTML view page. Following code to use show the product details, add into the show.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
@extends('layouts.pageLayout') @section('page_content') <style type="text/css"> .cust-table td{ padding: 10px; } </style> <div class="row"> <div class="col-lg-offset-3 col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> View Product Details </div> <div class="panel-body"> <table class="cust-table"> <tr> <th width="30%">Name</th><td>:</td><td width="69%">{{ $product->name }}</td> </tr> <tr> <th>Description</th><td>:</td><td>{{ $product->description }}</td> </tr> <tr> <th>Created At</th><td>:</td><td>{{ $product->created_at }}</td> </tr> <tr> <td colspan="3"><a href="{{ route('product.index') }}" class="btn btn-primary"> Back</a></td> </tr> </table> </div> </div> </div> </div> @endsection |
Step 11: Edit or Update existing details
In this section, we can update or edit the existing product details with a help of primary key. Following code to use fetch the product details and update it and submit the form. It will update the details in a database. Use the below code and save the file name as edit.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
@extends('layouts.pageLayout') @section('page_content') <div class="row"> <div class="col-lg-offset-3 col-lg-6"> @if($errors->any()) <div class="alert alert-danger"> @foreach($errors->all() as $error) <p>{{ $error }}</p> @endforeach() </div> @endif <div class="panel panel-default"> <div class="panel-heading"> Update Product details </div> <div class="panel-body"> {{ Form::open(array('url' => route('product.update', $product->id), 'method' => 'POST', 'name'=>'fk-input-form', 'id'=>'fs-forms')) }} <div class="form-group"> {{ Form::label('product_name', 'Product Name', ['class' => 'required']) }} {{ Form::text('name', $product->name, ['id'=>'product_name', 'class' => 'form-control', 'placeholder'=>'Product Name'] ) }} </div> <div class="form-group"> {{ Form::label('description', 'Description', ['class' => 'required']) }} {{ Form::textarea('description', $product->description, ['id'=>'description', 'class' => 'form-control', 'placeholder'=>'Description'] ) }} </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-6"> <input type="submit" class="btn btn-success" value="Update Product" /> <a href="{{ route('product.index') }}" class="btn btn-primary">Back</a> </div> </div> {{ Form::close() }} </div> </div> </div> </div> @endsection |
Step 12: Running our application
Everything it’s done Now we can run the Product CRUD procedures with corresponding URLs defined in routes.
example.com/products –> Show the index page
example.com/products/add –> Add new product details
example.com/products/show/{product_id} –> View or read the particular product details
example.com/products/edit/{product_id} –> Fetch the product details for edit and update in DB