Laravel 5.6中的CURD操作(程式碼範例詳解)

藏色散人
發布: 2023-04-05 12:50:01
原創
3777 人瀏覽過






Laravel 5.6中的CURD操作(程式碼範例詳解)在本篇文章中,我將給大家分享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(&#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;);
    }
}
登入後複製

第4步:新增resource路由

在這個步驟中,我們需要為產品crud應用新增resource路由。所以打開routes / web.php檔案並加入以下路由。

routes/web.php

Route::resource(&#39;products&#39;,&#39;ProductController&#39;);
登入後複製

第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(&#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;);
    }
}
登入後複製

#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 = [
        &#39;name&#39;, &#39;detail&#39;
    ];
}
登入後複製

第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(&#39;content&#39;)
</div>

</body>
</html>
登入後複製

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
登入後複製

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
登入後複製

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
登入後複製

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
登入後複製

現在,我們準備執行我們的crud應用程式的例子,所以執行以下命令快速運行:

php artisan serve
登入後複製

最後你就可以在瀏覽器上打開下面的網址進行查看測試:

http://localhost:8000/products
登入後複製

本篇文章就是關於Laravel 5.6中的CURD操作即創建,讀取,更新和刪除操作,希望對需要的朋友有幫助!





########### # ###

以上是Laravel 5.6中的CURD操作(程式碼範例詳解)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!