旗下导航:搜·么
当前位置:网站首页 > PHP教程 > 正文

Laravel 5.6中的CURD操纵(代码示例详解)【php教程】

作者:搜搜PHP网发布时间:2019-11-26分类:PHP教程浏览:86


导读:在本篇文章中,我将给人人分享laravel5.6版本中的基础crud(建立,读取,更新和删除)运用程序模块。你能够根据下面的步骤在laravel5.6中建立CRUD运用程序。...
在本篇文章中,我将给人人分享laravel 5.6版本中的基础crud(建立,读取,更新和删除)运用程序模块。你能够根据下面的步骤在laravel 5.6中建立CRUD运用程序。

Laravel是一个盛行的开源PHP MVC框架,具有很多高等开辟功用。假如你是laravel 5.6运用程序中的进修者或初学者,更多地相识或进修crud运用程序总是有很大协助的。(相干laravel视频教程:《最新laravel商城实战视频教程》)

下面我将建立insert(插进去)、update(更新)、delete(删除)和view(检察)和产物的分页示例。你只需建立新产物,检察产物,编辑产物并从列表中删除产物即可。

第1步:装置Laravel 5.6

能够在终端中运转 create-project 敕令来装置 Laravel:

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

(相干引荐:《怎样经由过程composer装置Laravel框架?》)

第2步:数据库设置

完成装置后,我们将为laravel 5.6的crud运用程序举行数据库设置,比方数据库称号,用户名,暗码等。所以,让我们翻开.env文件并填写相干信息,以下:

.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)

第3步:建立产物表和模子

我们将为产物建立crud运用程序。所以我们必需运用Laravel 5.6 php artisan敕令建立产物表的迁徙(migrations),起首运用以下敕令:

php artisan make:migration create_products_table --create=products

在实行此敕令以后,你能够在途径database/migrations中找到一个文件,而且必需将以下代码放在migrations文件中以用于建立products表。

<?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('detail');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

第4步:增加resource路由

在这个步骤中,我们须要为产物crud运用增加resource路由。所以翻开routes / web.php文件并增加以下路由。

routes/web.php

Route::resource('products','ProductController');

第5步:建立ProductController

如今,我们应当建立一个新的控制器ProductController。因而要运转以下敕令并建立新的控制器。下面的控制器用于建立resource控制器。

建立ProductController

php artisan make:controller ProductController --resource --model=Product

鄙人面的敕令以后,你将在这个途径app/Http/Controllers/ProductController.php中找到新的文件。

在这个控制器中,默许情况下将建立7个要领以下所示:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

因而,让我们复制下面的代码并将其放到ProductController.php文件中。

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('products.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('products.create');
    }

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

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

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

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

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

    /**
     * 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([
            'name' => 'required',
            'detail' => 'required',
        ]);

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

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

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

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }
}

OK,运转下面敕令后,你会找到app/Product.php,并将下面的内容放入Product.php文件中:

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 = [
        'name', 'detail'
    ];
}

第6步:建立Blade文件

如今我们进入末了一步。在这一步中,我们只须要建立blade文件。所以我们重要须要建立规划文件,然后建立新的文件夹“products”,然后建立crud app的blade文件。末了须要建立以下blade文件:

1) layout.blade.php

2) index.blade.php

3) show.blade.php

4) form.blade.php

5) create.blade.php

6) edit.blade.php

让我们建立下面的文件,并放入下面的代码。

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('content')
</div>

</body>
</html>

resources/views/products/index.blade.php

@extends('products.layout')

@section('content')
    <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('products.create') }}"> Create 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->detail }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id) }}" method="POST">

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

                    @csrf
                    @method('DELETE')

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

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

@endsection

resources/views/products/show.blade.php

@extends('products.layout')

@section('content')
    <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('products.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->detail }}
            </div>
        </div>
    </div>
@endsection

resources/views/products/create.blade.php

@extends('products.layout')

@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('products.index') }}"> 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('products.store') }}" 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

resources/views/products/edit.blade.php

@extends('products.layout')

@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('products.index') }}"> 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('products.update',$product->id) }}" method="POST">
        @csrf
        @method('PUT')

         <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

如今,我们预备运转我们的crud运用程序的例子,所以运转以下敕令疾速运转:

php artisan serve

末了你就能够在浏览器上翻开下面的网址举行检察测试:

http://localhost:8000/products

本篇文章就是关于Laravel 5.6中的CURD操纵即建立,读取,更新和删除操纵,愿望对须要的朋侪有所协助!

以上就是Laravel 5.6中的CURD操纵(代码示例详解)的细致内容,更多请关注ki4网别的相干文章!

标签:Laravel 5.6CURD操作