Home > Backend Development > PHP Tutorial > CURD operations in Laravel 5.6 (detailed code examples)

CURD operations in Laravel 5.6 (detailed code examples)

藏色散人
Release: 2023-04-05 12:50:01
Original
3841 people have browsed it






##In this article, I will share with you the basic crud (create, read, update and delete) application module in laravel 5.6 version. You can follow the steps below to create a CRUD application in laravel 5.6.

CURD operations in Laravel 5.6 (detailed code examples)

Laravel is a popular open source PHP MVC framework with many advanced development features. If you are a learner or beginner in laravel 5.6 application, it always helps a lot to know or learn more about crud application. (Related laravel video tutorial: "

Latest Laravel Mall Practical Video Tutorial")

Below I will create insert, update, delete and view and product pagination example. You just create new products, view products, edit products and remove products from the list.

Step 1: Install Laravel 5.6

You can run the create-project command in the terminal to install Laravel:

composer create-project --prefer-dist laravel/laravel blog
Copy after login

(Related recommendations: "

How to install the Laravel framework through composer?》)

Step 2: Database configuration

After completing the installation, we will provide crud for laravel 5.6 The application performs database configuration such as database name, username, password, etc. So, let’s open the .env file and fill in the relevant information as follows:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Copy after login

Step 3: Create Product Table and Model

We will create crud application for product. So we have to create the migrations of the product table using Laravel 5.6 php artisan command, first use the following command:

php artisan make:migration create_products_table --create=products
Copy after login

After executing this command, you can create the migrations in the path

database/migrations A file is found and the following code must be placed in the migrations file for creating the products table.

<?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(&#39;products&#39;, function (Blueprint $table) {
            $table->increments(&#39;id&#39;);
            $table->string(&#39;name&#39;);
            $table->text(&#39;detail&#39;);
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(&#39;products&#39;);
    }
}
Copy after login

Step 4: Add resource routing

In this step, we need to add resource routing for the product crud application. So open routes/web.php file and add the following routes.

routes/web.php

Route::resource(&#39;products&#39;,&#39;ProductController&#39;);
Copy after login

Step 5: Create ProductController

Now, we should create a new controller ProductController. So run the following command and create a new controller. The following controller is used to create the resource controller.

Create ProductController

php artisan make:controller ProductController --resource --model=Product
Copy after login

After the following command, you will find the new file in this path app/Http/Controllers/ProductController.php.

In this controller, 7 methods will be created by default as follows:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy( )

So, let’s copy the code below and put it in the ProductController.php file.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(5);

        return view(&#39;products.index&#39;,compact(&#39;products&#39;))
            ->with(&#39;i&#39;, (request()->input(&#39;page&#39;, 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view(&#39;products.create&#39;);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        request()->validate([
            &#39;name&#39; => &#39;required&#39;,
            &#39;detail&#39; => &#39;required&#39;,
        ]);

        Product::create($request->all());

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product created successfully.&#39;);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view(&#39;products.show&#39;,compact(&#39;product&#39;));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view(&#39;products.edit&#39;,compact(&#39;product&#39;));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
         request()->validate([
            &#39;name&#39; => &#39;required&#39;,
            &#39;detail&#39; => &#39;required&#39;,
        ]);

        $product->update($request->all());

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product updated successfully&#39;);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product deleted successfully&#39;);
    }
}
Copy after login

OK, after running the following command, you will find app/Product.php and put the following content into the Product.php file :

app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        &#39;name&#39;, &#39;detail&#39;
    ];
}
Copy after login

Step 6: Create Blade file

Now we enter the final step. In this step, we just need to create the blade file. So we mainly need to create the layout file, then create a new folder "products", and then create the blade file of the crud app. Finally, you need to create the following blade files:

1) layout.blade.php

2) index.blade.php

3) show.blade.php

4) form.blade.php

5) create.blade.php

6) edit.blade.php

Let us create the following file and put Enter the code below.

resources/views/products/layout.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 5.6 CRUD Application</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(&#39;content&#39;)
</div>

</body>
</html>
Copy after login

resources/views/products/index.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 5.6 CRUD Example from scratch</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route(&#39;products.create&#39;) }}"> Create New Product</a>
            </div>
        </div>
    </div>

    @if ($message = Session::get(&#39;success&#39;))
        <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->detail }}</td>
            <td>
                <form action="{{ route(&#39;products.destroy&#39;,$product->id) }}" method="POST">

                    <a class="btn btn-info" href="{{ route(&#39;products.show&#39;,$product->id) }}">Show</a>
                    <a class="btn btn-primary" href="{{ route(&#39;products.edit&#39;,$product->id) }}">Edit</a>

                    @csrf
                    @method(&#39;DELETE&#39;)

   
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>

    {!! $products->links() !!}

@endsection
Copy after login

resources/views/products/show. blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route(&#39;products.index&#39;) }}"> 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->detail }}
            </div>
        </div>
    </div>
@endsection
Copy after login

resources/views/products/create.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <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(&#39;products.index&#39;) }}"> Back</a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <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 action="{{ route(&#39;products.store&#39;) }}" method="POST">
        @csrf

         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
                </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>

    </form>

@endsection
Copy after login

resources/views/products/edit.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <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(&#39;products.index&#39;) }}"> Back</a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <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 action="{{ route(&#39;products.update&#39;,$product->id) }}" method="POST">
        @csrf
        @method(&#39;PUT&#39;)

         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
                </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>

    </form>

@endsection
Copy after login

Now, we are ready Run our crud application example, so run the following command to quickly run:

php artisan serve
Copy after login

Finally you can open the following URL on the browser to view the test:

http://localhost:8000/products
Copy after login

This article is Regarding the CURD operations in Laravel 5.6, namely create, read, update and delete operations, I hope it will be helpful to friends in need!






#

The above is the detailed content of CURD operations in Laravel 5.6 (detailed code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template