• 技术文章 >php框架 >Laravel

    新鲜出炉的Laravel 速查表不要错过!

    藏色散人藏色散人2021-11-01 15:50:39转载756

    下面由Laravel教程栏目带大家介绍新鲜出炉的Laravel 速查表,希望对大家有所帮助!


    Laravel 速查表

    项目命令

    // 创建新项目
    $ laravel new projectName
    
    // 运行 服务/项目
    $ php artisan serve
    
    // 查看指令列表
    $ php artisan list
    
    // 帮助
    $ php artisan help migrate
    
    // Laravel 控制台
    $ php artisan tinker
    
    // 查看路由列表
    $ php artisan route:list

    公共指令

    // 数据库迁移
    $ php artisan migrate
    
    // 数据填充
    $ php artisan db:seed
    
    // 创建数据表迁移文件
    $ php artisan make:migration create_products_table
    
    // 生成模型选项: 
    // -m (migration), -c (controller), -r (resource controllers), -f (factory), -s (seed)
    $ php artisan make:model Product -mcf
    
    // 生成控制器
    $ php artisan make:controller ProductsController
    
    // 表更新字段
    $ php artisan make:migration add_date_to_blogposts_table
    
    // 回滚上一次迁移
    php artisan migrate:rollback
    
    // 回滚所有迁移
    php artisan migrate:reset
    
    // 回滚所有迁移并刷新
    php artisan migrate:refresh
    
    // 回滚所有迁移,刷新并生成数据
    php artisan migrate:refresh --seed

    创建和更新数据表

    // 创建数据表
    $ php artisan make:migration create_products_table
    
    // 创建数据表(迁移示例)
    Schema::create('products', function (Blueprint $table) {
        // 自增主键
        $table->id();
        // created_at 和 updated_at 字段
        $table->timestamps();
        // 唯一约束
        $table->string('modelNo')->unique();
        // 非必要
        $table->text('description')->nullable();
        // 默认值
        $table->boolean('isActive')->default(true); 
        // 索引
        $table->index(['account_id', 'created_at']);
        // 外键约束
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
    });
    
    // 更新表(迁移示例)
    $ php artisan make:migration add_comment_to_products_table
    
    // up()
    Schema::table('users', function (Blueprint $table) {
        $table->text('comment');
    });
    
    // down()
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('comment');
    });

    模型

    // 模型质量指定列表排除属性
    protected $guarded = []; // empty == All
    
    // 或者包含属性的列表
    protected $fillable = ['name', 'email', 'password',];
    
    // 一对多关系 (一条帖子对应多条评论)
    public function comments() 
    {
        return $this->hasMany(Comment:class); 
    }
    
    // 一对多关系 (多条评论在一条帖子下) 
    public function post() 
    {                            
        return $this->belongTo(Post::class); 
    }
    
    // 一对一关系 (作者和个人简介)
    public function profile() 
    {
        return $this->hasOne(Profile::class); 
    }
    
    // 一对一关系 (个人简介和作者) 
    public function author() 
    {                            
        return $this->belongTo(Author::class); 
    }
    
    // 多对多关系
    // 3 张表 (帖子, 标签和帖子-标签)
    // 帖子-标签:post_tag (post_id, tag_id)
    
    // 「标签」模型中...
    public function posts()
        {
            return $this->belongsToMany(Post::class);
        }
    
    // 帖子模型中...
    public function tags()
        {
            return $this->belongsToMany(Tag::class);
        }

    Factory

    // 例子: database/factories/ProductFactory.php
    public function definition() {
        return [
            'name' => $this->faker->text(20),
            'price' => $this->faker->numberBetween(10, 10000),
        ];
    }
    // 所有 fakers 选项 : https://github.com/fzaninotto/Faker

    Seed

    // 例子: database/seeders/DatabaseSeeder.php
    public function run() {
        Product::factory(10)->create();
    }

    运行 Seeders

    $ php artisan db:seed
    // 或者 migration 时执行
    $ php artisan migrate --seed

    Eloquent ORM

    // 新建 
    $flight = new Flight;
    $flight->name = $request->name;
    $flight->save();
    
    // 更新 
    $flight = Flight::find(1);
    $flight->name = 'New Flight Name';
    $flight->save();
    
    // 创建
    $user = User::create(['first_name' => 'Taylor','last_name' => 'Otwell']); 
    
    // 更新所有:  
    Flight::where('active', 1)->update(['delayed' => 1]);
    
    // 删除 
    $current_user = User::Find(1)
    $current_user.delete(); 
    
    // 根据 id 删除:  
    User::destroy(1);
    
    // 删除所有
    $deletedRows = Flight::where('active', 0)->delete();
    
    // 获取所有
    $items = Item::all(). 
    
    // 根据主键查询一条记录
    $flight = Flight::find(1);
    
    // 如果不存在显示 404
    $model = Flight::findOrFail(1); 
    
    // 获取最后一条记录
    $items = Item::latest()->get()
    
    // 链式 
    $flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();
    
    // Where
    Todo::where('id', $id)->firstOrFail()  
    
    // Like 
    Todos::where('name', 'like', '%' . $my . '%')->get()
    
    // Or where
    Todos::where('name', 'mike')->orWhere('title', '=', 'Admin')->get();
    
    // Count
    $count = Flight::where('active', 1)->count();
    
    // Sum
    $sum = Flight::where('active', 1)->sum('price');
    
    // Contain?
    if ($project->$users->contains('mike'))

    路由

    // 基础闭包路由
    Route::get('/greeting', function () {
        return 'Hello World';
    });
    
    // 视图路由快捷方式
    Route::view('/welcome', 'welcome');
    
    // 路由到控制器
    use App\Http\Controllers\UserController;
    Route::get('/user', [UserController::class, 'index']);
    
    // 仅针对特定 HTTP 动词的路由
    Route::match(['get', 'post'], '/', function () {
        //
    });
    
    // 响应所有 HTTP 请求的路由
    Route::any('/', function () {
        //
    });
    
    // 重定向路由
    Route::redirect('/clients', '/customers');
    
    // 路由参数
    Route::get('/user/{id}', function ($id) {
        return 'User '.$id;
    });
    
    // 可选参数
    Route::get('/user/{name?}', function ($name = 'John') {
        return $name;
    });
    
    // 路由命名
    Route::get(
        '/user/profile',
        [UserProfileController::class, 'show']
    )->name('profile');
    
    // 资源路由
    Route::resource('photos', PhotoController::class);
    
    GET /photos index   photos.index
    GET /photos/create  create  photos.create
    POST    /photos store   photos.store
    GET /photos/{photo} show    photos.show
    GET /photos/{photo}/edit    edit    photos.edit
    PUT/PATCH   /photos/{photo} update  photos.update
    DELETE  /photos/{photo} destroy photos.destroy
    
    // 完整资源路由
    Route::resource('photos.comments', PhotoCommentController::class);
    
    // 部分资源路由
    Route::resource('photos', PhotoController::class)->only([
        'index', 'show'
    ]);
    
    Route::resource('photos', PhotoController::class)->except([
        'create', 'store', 'update', 'destroy'
    ]);
    
    // 使用路由名称生成 URL
    $url = route('profile', ['id' => 1]);
    
    // 生成重定向...
    return redirect()->route('profile');
    
    // 路由组前缀
    Route::prefix('admin')->group(function () {
        Route::get('/users', function () {
            // Matches The "/admin/users" URL
        });
    });
    
    // 路由模型绑定
    use App\Models\User;
    Route::get('/users/{user}', function (User $user) {
        return $user->email;
    });
    
    // 路由模型绑定(id 除外)
    use App\Models\User;
    Route::get('/posts/{post:slug}', function (Post $post) {
        return view('post', ['post' => $post]);
    });
    
    // 备选路由
    Route::fallback(function () {
        //
    });

    缓存

    // 路由缓存
    php artisan route:cache
    
    // 获取或保存(键,存活时间,值)
    $users = Cache::remember('users', now()->addMinutes(5), function () {
        return DB::table('users')->get();
    });

    控制器

    // 设置校验规则
    protected $rules = [
        'title' => 'required|unique:posts|max:255',
        'name' => 'required|min:6',
        'email' => 'required|email',
        'publish_at' => 'nullable|date',
    ];
    
    // 校验
    $validatedData = $request->validate($rules)
    
    // 显示 404 错误页
    abort(404, 'Sorry, Post not found')
    
    // Controller CRUD 示例
    Class ProductsController
    {
    
       public function index()
       {
           $products = Product::all();
    
           // app/resources/views/products/index.blade.php
           return view('products.index', ['products', $products]); 
       }
    
       public function create()
       {
           return view('products.create');
       }
    
       public function store()
       {
           Product::create(request()->validate([
               'name' => 'required',
               'price' => 'required',
               'note' => 'nullable'
           ]));
    
           return redirect(route('products.index'));
       }
    
       // 模型注入方法
       public function show(Product $product)
       {
           return view('products.show', ['product', $product]); 
       }
    
       public function edit(Product $product)
       {
           return view('products.edit', ['product', $product]); 
       }
    
       public function update(Product $product)
       {
           Product::update(request()->validate([
               'name' => 'required',
               'price' => 'required',
               'note' => 'nullable'
           ]));
    
           return redirect(route($product->path()));
       }
    
       public function delete(Product $product)
       {
            $product->delete();
            return redirect("/contacts");
       }
    }
    
    // 获取 Query Params www.demo.html?name=mike
    request()->name //mike
    
    // 获取 Form data 传参(或默认值)
    request()->input('email', 'no@email.com')

    Template

    <!-- 路由名 -->
    <a href="{{ route('routeName.show', $id) }}">
    
    <!-- 模板继承 -->
    @yield('content')  <!-- layout.blade.php -->
    @extends('layout')
    @section('content') … @endsection
    
    <!-- 模板 include -->
    @include('view.name', ['name' => 'John'])
    
    <!-- 模板变量 -->
    {{ var_name }} 
    
    <!-- 原生安全模板变量 --> 
    { !! var_name !! }
    
    <!-- 迭代 -->
    @foreach ($items as $item)
       {{ $item.name }}
       @if($loop->last) 
           $loop->index 
       @endif
    @endforeach
    
    <!-- 条件 -->
    @if ($post->id === 1) 
        'Post one' 
    @elseif ($post->id === 2)
        'Post two!' 
    @else 
        'Other' 
    @endif
    
    <!--Form 表单 -->
    <form method="POST" action="{{ route('posts.store') }}">
    
    @method(‘PUT’)
    @csrf
    
    <!-- Request 路径匹配 -->
    {{ request()->is('posts*') ? 'current page' : 'not current page' }} 
    
    <!-- 路由是否存在 -->
    @if (Route::has('login'))
    
    <!-- Auth blade 变量 -->
    @auth 
    @endauth 
    @guest
    
    <!-- 当前用户 -->
    {{ Auth::user()->name }}
    
    <!-- Validations 验证错误 -->
    @if ($errors->any())
        <p class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </p>
    @endif
    
    <!-- 检查具体属性 -->
    <input id="title" type="text" class="@error('title') is-invalid @enderror">
    
    <!-- 上一次请求数据填充表单 -->
    {{ old('name') }}

    不使用模型访问数据库

    use Illuminate\Support\Facades\DB;
    $user = DB::table('users')->first();
    $users = DB::select('select name, email from users');
    DB::insert('insert into users (name, email, password) value(?, ?, ?)', ['Mike', 'mike@hey.com', 'pass123']);
    DB::update('update users set name = ? where id = 1', ['eric']);
    DB::delete('delete from users where id = 1');

    帮助函数

    // 显示变量内容并终止执行
    dd($products)
    
    // 将数组转为Laravel集合
    $collection = collect($array);
    
    // 按描述升序排序
    $ordered_collection = $collection->orderBy(‘description’);
    
    // 重置集合键
    $ordered_collection = $ordered_collection->values()->all();
    
    // 返回项目完整路径
    app\ : app_path();
    resources\ : resource_path();
    database\ :database_path();

    闪存 和 Session

    // 闪存(只有下一个请求)
    $request->session()->flash('status', 'Task was successful!');
    
    // 带重定向的闪存
    return redirect('/home')->with('success' => 'email sent!');
    
    // 设置 Session
    $request->session()->put('key', 'value');
    
    // 获取 session
    $value = session('key');
    If session: if ($request->session()->has('users'))
    
    // 删除 session
    $request->session()->forget('key');
    
    // 在模板中显示 flash
    @if (session('message')) {{ session('message') }} @endif

    HTTP Client

    // 引入包
    use Illuminate\Support\Facades\Http;
    
    // Http get 方式请求
    $response = Http::get('www.thecat.com')
    $data = $response->json()
    
    // Http get 带参方式请求
    $res = Http::get('www.thecat.com', ['param1', 'param2'])
    
    // Http post 带请求体方式请求
    $res = Http::post('http://test.com', ['name' => 'Steve','role' => 'Admin']);
    
    // 带令牌认证方式请求
    $res = Http::withToken('123456789')->post('http://the.com', ['name' => 'Steve']);
    
    // 带请求头方式发起请求
    $res = Http::withHeaders(['type'=>'json'])->post('http://the.com', ['name' => 'Steve']);

    Storage (用于存储在本地文件或者云端服务的助手类)

    // Public 驱动配置: Local storage/app/public
    Storage::disk('public')->exists('file.jpg')) 
    // S3 云存储驱动配置: storage: 例如 亚马逊云:
    Storage::disk('s3')->exists('file.jpg')) 
    
    // 在 web 服务中暴露公共访问内容
    php artisan storage:link
    
    // 在存储文件夹中获取或者保存文件
    use Illuminate\Support\Facades\Storage;
    Storage::disk('public')->put('example.txt', 'Contents');
    $contents = Storage::disk('public')->get('file.jpg'); 
    
    // 通过生成访问资源的 url 
    $url = Storage::url('file.jpg');
    // 或者通过公共配置的绝对路径
    <img src={{ asset('storage/image1.jpg') }}/>
    
    // 删除文件
    Storage::delete('file.jpg');
    
    // 下载文件
    Storage::disk('public')->download('export.csv');

    从 github 安装新项目

    $ git clone {project http address} projectName
    $ cd projectName
    $ composer install
    $ cp .env.example .env
    $ php artisan key:generate
    $ php artisan migrate
    $ npm install

    Heroku 部署

    // 本地(MacOs)机器安装 Heroku 
    $ brew tap heroku/brew && brew install heroku
    
    // 登陆 heroku (不存在则创建)
    $ heroku login
    
    // 创建 Profile 
    $ touch Profile
    
    // 保存 Profile
    web: vendor/bin/heroku-php-apache2 public/

    Rest API (创建 Rest API 端点)

    API 路由 ( 所有 api 路由都带 'api/' 前缀 )

    // routes/api.php
    Route::get('products', [App\Http\Controllers\ProductsController::class, 'index']);
    Route::get('products/{product}', [App\Http\Controllers\ProductsController::class, 'show']);
    Route::post('products', [App\Http\Controllers\ProductsController::class, 'store']);

    API 资源 (介于模型和 JSON 响应之间的资源层)

    $ php artisan make:resource ProductResource

    资源路由定义文件

    // app/resource/ProductResource.php
    public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'price' => $this->price,
                'custom' => 'This is a custom field',
            ];
        }

    API 控制器 (最佳实践是将您的 API 控制器放在 app/Http/Controllers/API/v1/中)

    public function index() {
            //$products = Product::all();
            $products = Product::paginate(5);
            return ProductResource::collection($products);
        }
    
        public function show(Product $product) {
            return new ProductResource($product);
        }
    
        public function store(StoreProductRequest $request) {
            $product = Product::create($request->all());
            return new ProductResource($product);
        }

    API 令牌认证

    首先,您需要为特定用户创建一个 Token。【相关推荐:最新的五个Laravel视频教程

    $user = User::first();
    $user->createToken('dev token');
    // plainTextToken: "1|v39On3Uvwl0yA4vex0f9SgOk3pVdLECDk4Edi4OJ"

    然后可以一个请求使用这个令牌

    GET api/products (Auth Bearer Token: plainTextToken)

    授权规则
    您可以使用预定义的授权规则创建令牌

    $user->createToken('dev token', ['product-list']);
    
    // in controllers
    if !auth()->user()->tokenCan('product-list') {
        abort(403, "Unauthorized");
    }

    原文地址:https://dev.to/ericchapman/my-beloved-laravel-cheat-sheet-3l73

    译文地址:https://learnku.com/laravel/t/62150

    以上就是新鲜出炉的Laravel 速查表不要错过!的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:learnku,如有侵犯,请联系admin@php.cn删除
    专题推荐:Laravel
    上一篇:详解Laravel使用多数据库的方法(附代码示例) 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • laravel new blog安装为什么会出错?(解析及方法)• 解析Laravel事件系统的使用方法• 详解怎么在Laravel中部署vue• 详解Laravel使用多数据库的方法(附代码示例)
    1/1

    PHP中文网