• Simple Add, Edit, View & Delete operations In Laravel5 Using MAMP & Mysql


    Please try step by step to make a simple application in Laravel.

    Step1: Install Laravel

    Go to htdocs in Terminal  & run the following command.
     Composer create-project Laravel/Laravel productapp
    (it will create a project as productapp in htdocs)

    Step2: Install laravelcollective/html for Form class

    a.    Go to terminal & run  following command.
    Composer require laravelcollective/html

    b.    Go to /Applications/MAMP/htdocs/blog/config/app.php .
    Add the following line in providers array as in following image.
                 Collective\Html\HtmlServiceProvider::class,

             

         Add the following lines in aliases array as in following image.


    'Form' => Collective\Html\FormFacade::class,
    'HTML' => Collective\Html\HtmlFacade::class,



    Step 3: Create a database in phpMyAdmin(ex. Productapp) & configure database connections.

    ·      Go to config->database.php and config ur database as following

    'mysql' => [
                'driver' => 'mysql',
                'host' => env('DB_HOST', 'localhost'),
                'port' => env('DB_PORT', '3306'),
                'database' => env('DB_DATABASE', 'productapp’'),
                'username' => env('DB_USERNAME', 'root'),
                'password' => env('DB_PASSWORD', 'root'),
                'unix_socket' => env('DB_SOCKET', ''),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => '',
                'strict' => true,
                'engine' => null,
            ],

    ·      Go to  .env and change the database config as follows.

    DB_CONNECTION=mysql
    DB_HOST=localhost
    DB_PORT=3306
    DB_DATABASE=productapp
    DB_USERNAME=root
    DB_PASSWORD=root


    Step 4: Create table & model

    ·      Create migrations for products table by running following command.

     php artisan make:migration create products

    After this command you will see a migration file(like 2018_09_07_100452_create_products_table) in path : database/migrations and you have to paste the following code in the migration file.

    <?php

    use Illuminate\Support\Facades\Schema;
    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('details');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
                    Schema::drop("products");

        }
    }


    ·      Save the file & run the following command.
       php artisan migrate
    After running the command, product table will be created in database. you can check.


    Step 5: Create model for product table.

    Create file in following path app/Product.php and put the following code in Product.php file:

    app/Product.php

    <?php

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Product extends Model
    {
        public $fillable = ['name','details'];
    }

    Step 6: Add Route

    put bellow line of code in your route file.

    The file path can be different for different versions of Laravel.For Laravel 5.4 it is routes/web.php
    Or it can be in app/Http/routes.php
    Route::resource('productCRUD','ProductCRUDController');

    <?php

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */

    Route::get('/', function () {
        return view('welcome');
    });
    Route::resource('productCRUD','ProductCRUDController');

    Step 7: Create a Controller.
    ·      Go to terminal & type the following command
    php artisan make:controller ProductCRUDController

    ·      Now go to app/Http/Controllers/ProductCRUDController.php & paste the following codes. All routes will manage by this controller.

         <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\Product;

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\Product;
    class ProductCRUDController extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index(Request $request)
        {
            $products= Product::orderBy('id','DESC')->paginate(5);
            return view('ProductCRUD.index',compact('products'))
                ->with('i', ($request->input('page', 1) - 1) * 5);
        }
        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            return view('ProductCRUD.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',
                'details' => 'required',
            ]);
            Product::create($request->all());
            return redirect()->route('productCRUD.index')
                            ->with('success','Product created successfully');
        }
        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            $product= Product::find($id);
            return view('ProductCRUD.show',compact('product'));
        }
        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $product= Product::find($id);
            return view('ProductCRUD.edit',compact('product'));
        }
        /**
         * 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',
                'details' => 'required',
            ]);
            Product::find($id)->update($request->all());
            return redirect()->route('productCRUD.index')
                            ->with('success','Product updated successfully');
        }
        /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {
            Product::find($id)->delete();
            return redirect()->route('productCRUD.index')
                            ->with('success','Product deleted successfully');
        }
    }

    Step 8: Create view files.

    ·      Create  1 folder as  resources in resources/views and create default.blade.php 
               as resources/views/default.blade.php and put the following codes.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel CRUD</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    </head>
    <body>

    <div class="container">
        @yield('content')
    </div>

    </body>
    </html>


    ·      Create ProductCRUD folder in resources/views and create view file index.blade.php  as resources/views/ProductCRUD/index.blade.php & paste the following codes.

    @extends('layouts.default')
    @section('content')
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Products</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-success" href="{{ route('productCRUD.create') }}"> Add New Product</a>
                </div>
            </div>
        </div>
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
        @endif
        <table class="table table-bordered">
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Details</th>
                <th width="280px">Action</th>
            </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name}}</td>
            <td>{{ $product->details}}</td>
            <td>
                <a class="btn btn-info" href="{{ route('productCRUD.show',$product->id) }}">Show</a>
                <a class="btn btn-primary" href="{{ route('productCRUD.edit',$product->id) }}">Edit</a>
                {!! Form::open(['method' => 'DELETE','route' => ['productCRUD.destroy', $product->id],'style'=>'display:inline']) !!}
                {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
                {!! Form::close() !!}
            </td>
        </tr>
        @endforeach
        </table>
        {!! $products->render() !!}
    @endsection



    ·      Create create.blade.php  resources/views/ProductCRUD/create.blade.php & paste the following code

    @extends('layouts.default')
    @section('content')
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Add New Product</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('productCRUD.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {!! Form::open(array('route' => 'productCRUD.store','method'=>'POST')) !!}
             @include('ProductCRUD.form')
        {!! Form::close() !!}
    @endsection




    ·      Create edit.blade.php  resources/views/ProductCRUD/edit.blade.php & paste the following code.

    @extends('layouts.default')

    @section('content')
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Edit Product</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('productCRUD.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {!! Form::model($product, ['method' => 'PATCH','route' => ['productCRUD.update', $product->id]]) !!}
            @include('ProductCRUD.form')
        {!! Form::close() !!}
    @endsection


    ·      Create form.blade.php  resources/views/ProductCRUD/form.blade.php & paste the following code.

    <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Details:</strong>
                    {!! Form::textarea('details', null, array('placeholder' => 'Details','class' => 'form-control','style'=>'height:100px')) !!}
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    ·      Create show.blade.php  resources/views/ProductCRUD/show.blade.php & paste the following code.


    @extends('layouts.default')

    @section('content')
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2> Show Products</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('productCRUD.index') }}"> Back</a>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    {{ $product->name}}
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Details:</strong>
                    {{ $product->details}}
                </div>
            </div>
        </div>
    @endsection

    Step 9: Now run the following command in terminal

    Php artisan serve

    Step 10: type productCRUD followed by your localhost url.

    Then you can perform CRUD operations.
    The url can be like
    localhost/productCRUD








  • You might also like

    No comments:

    Post a Comment