zoukankan      html  css  js  c++  java
  • PHP开发笔记(3)Laravel

    安装 PHP 开发环境

    PHP开发笔记(1)开发环境

    安装使用 Laravel

    $ composer global require laravel/installer
    $ export PATH=$PATH:~/.composer/vendor/bin
    # 创建新的应用程序
    $ laravel new blog
    # 或者
    $ composer create-project --prefer-dist laravel/laravel blog
    $ cd blog
    $ php artisan serve
    # http://localhost:8000
    

    示例

    Laravel 7 CRUD Example | Laravel 7 Tutorial For Beginners

    配置数据库

    修改 .env 文件的数据库配置部分

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel_blog
    DB_USERNAME=root
    DB_PASSWORD=
    

    数据库迁移

    创建数据库迁移命令文件

    $ php artisan make:migration create_products_table --create=products
    Created Migration: 2020_05_06_073654_create_products_table
    

    修改所生成的 database/migrations/2020_05_06_073654_create_products_table.php 文件

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateSupportFacadesSchema;
    
    class CreateProductsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('products', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->text('detail');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('products');
        }
    }
    

    执行数据库迁移

    $ php artisan migrate
    Migration table created successfully.
    Migrating: 2014_10_12_000000_create_users_table
    Migrated:  2014_10_12_000000_create_users_table (0.03 seconds)
    Migrating: 2019_08_19_000000_create_failed_jobs_table
    Migrated:  2019_08_19_000000_create_failed_jobs_table (0.01 seconds)
    Migrating: 2020_05_06_073654_create_products_table
    Migrated:  2020_05_06_073654_create_products_table (0.01 seconds)
    

    添加路由

    修改 routes/web.php

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

    添加控制器和模型

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

    模型类代码

    app/Product.php

    <?php
      
    namespace App;
      
    use IlluminateDatabaseEloquentModel;
       
    class Product extends Model
    {
        protected $fillable = [
            'name', 'detail'
        ];
    }
    

    控制器类代码

    app/Http/Controllers/ProductController.php

    <?php
      
    namespace AppHttpControllers;
      
    use AppProduct;
    use IlluminateHttpRequest;
      
    class ProductController extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return IlluminateHttpResponse
         */
        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 IlluminateHttpResponse
         */
        public function create()
        {
            return view('products.create');
        }
      
        /**
         * Store a newly created resource in storage.
         *
         * @param  IlluminateHttpRequest  $request
         * @return IlluminateHttpResponse
         */
        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  AppProduct  $product
         * @return IlluminateHttpResponse
         */
        public function show(Product $product)
        {
            return view('products.show',compact('product'));
        }
       
        /**
         * Show the form for editing the specified resource.
         *
         * @param  AppProduct  $product
         * @return IlluminateHttpResponse
         */
        public function edit(Product $product)
        {
            return view('products.edit',compact('product'));
        }
      
        /**
         * Update the specified resource in storage.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  AppProduct  $product
         * @return IlluminateHttpResponse
         */
        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  AppProduct  $product
         * @return IlluminateHttpResponse
         */
        public function destroy(Product $product)
        {
            $product->delete();
      
            return redirect()->route('products.index')
                            ->with('success','Product deleted successfully');
        }
    }
    

    视图代码

    resources/views/products/layout.blade.php

    <!DOCTYPE html>
    <html>
    <head>
        <title>Laravel 7 CRUD Application - ItSolutionStuff.com</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 7 CRUD Example from scratch - ItSolutionStuff.com</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/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
    

    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
    

    启动程序

    http://localhost:8000/products

  • 相关阅读:
    为sublime text2 添加SASS语法高亮
    下拉框点链接js
    [JavaScript] 初中级Javascript程序员必修学习目录
    判断页数及切换
    切换加上延迟加载js代码
    jquery 简单弹出层(转)
    左右滑动删除ListView条目Item--第三方开源--SwipeToDismiss
    使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)
    从一个URL下载原始数据,基于byte字节,得到byte数组
    动画气泡指示当前滑动值--第三方开源--DiscreteSeekbar
  • 原文地址:https://www.cnblogs.com/zwvista/p/12835993.html
Copyright © 2011-2022 走看看