这篇文章主要介绍“怎么使用Laravel命令”,在日常操作中,相信很多人在怎么使用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.phppublic function definition() { return [ 'name' => $this->faker->text(20), 'price' => $this->faker->numberBetween(10, 10000), ];}// 所有 fakers 选项 : https://github.com/fzaninotto/Faker
Seed
// 例子: database/seeders/DatabaseSeeder.phppublic 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();// WhereTodo::where('id', $id)->firstOrFail() // Like Todos::where('name', 'like', '%' . $my . '%')->get()// Or whereTodos::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.indexGET /photos/create create photos.createPOST /photos store photos.storeGET /photos/{photo} show photos.showGET /photos/{photo}/edit edit photos.editPUT/PATCH /photos/{photo} update photos.updateDELETE /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=mikerequest()->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/publicStorage::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// 保存 Profileweb: vendor/bin/heroku-php-apache2 public/
Rest API (创建 Rest API 端点)
API 路由 ( 所有 api 路由都带 'api/' 前缀 )
// routes/api.phpRoute::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.phppublic 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 controllersif !auth()->user()->tokenCan('product-list') { abort(403, "Unauthorized");}
到此,关于“怎么使用Laravel命令”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!