新鲜出炉的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 = AppFlight::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 AppHttpControllersUserController;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 AppModelsUser;Route::get('/users/{user}', function (User $user) {    return $user->email;});// 路由模型绑定(id 除外)use AppModelsUser;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

@yield('content')  @extends('layout')@section('content') … @endsection@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@method(‘PUT’)@csrf{{ request()->is('posts*') ? 'current page' : 'not current page' }} @if (Route::has('login'))@auth @endauth @guest{{ Auth::user()->name }}@if ($errors->any())    

    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach

@endif{{ old('name') }}

不使用模型访问数据库

use IlluminateSupportFacadesDB;$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');

帮助函数

酷表ChatExcel 酷表ChatExcel

北大团队开发的通过聊天来操作Excel表格的AI工具

酷表ChatExcel 48 查看详情 酷表ChatExcel

// 显示变量内容并终止执行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 IlluminateSupportFacadesHttp;// 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 IlluminateSupportFacadesStorage;Storage::disk('public')->put('example.txt', 'Contents');$contents = Storage::disk('public')->get('file.jpg'); // 通过生成访问资源的 url $url = Storage::url('file.jpg');// 或者通过公共配置的绝对路径新鲜出炉的Laravel 速查表不要错过!// 删除文件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', [AppHttpControllersProductsController::class, 'index']);Route::get('products/{product}', [AppHttpControllersProductsController::class, 'show']);Route::post('products', [AppHttpControllersProductsController::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");}

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/230161.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Claude如何优化回答质量 提示词编写技巧分享
上一篇 2025年11月3日 20:46:13
实现数据冗余与扩展:MySQL主从复制技术在集群环境中的应用案例
下一篇 2025年11月3日 20:46:18

相关推荐

  • Laravel控制器怎么创建_Laravel控制器创建与请求处理

    Laravel控制器处理请求,使用Artisan命令php artisan make:controller创建,带–resource参数可生成CRUD方法;通过引入Request类获取输入并验证数据,在路由文件中绑定URL与控制器方法,实现请求响应流程。 在 Laravel 中,控制器是…

    2026年9月22日
    600
  • Laravel 文件上传:解决数据库存储物理路径而非可访问 URL 的问题

    本教程旨在解决 laravel 文件上传后,数据库中存储文件物理路径而非可访问 url 的常见问题。通过分析 move() 方法的返回值,并引入 url() 辅助函数,我们将演示如何正确地将文件移动到指定目录,同时确保数据库记录的是可供前端访问的图片资源链接,从而避免图片无法正常显示。 在 Lara…

    2026年9月22日
    100
  • laravel如何使用Pipeline模式处理复杂逻辑_Laravel Pipeline模式处理复杂逻辑方法

    Laravel Pipeline通过将复杂流程拆分为多个独立处理步骤,实现代码解耦与职责分离。以用户注册为例,可依次执行发送欢迎邮件、分配角色、记录日志等操作,每个步骤由单独类实现__invoke方法,通过Pipeline::send($user)->through([…])-&g…

    2026年9月22日
    300
  • PHP日志记录怎么做_PHP中Monolog库实现灵活强大的日志系统

    Monolog是PHP中基于PSR-3标准的主流日志库,通过Composer安装后可轻松实现日志记录。使用Logger类创建实例并添加Handler(如StreamHandler写入文件、NativeMailerHandler邮件报警)来管理不同级别(debug、info、error等)日志输出,支…

    2026年9月22日
    300
  • PHP框架日志系统怎么记录错误_PHP框架日志系统配置指南

    PHP框架通过配置日志级别、通道和处理器,结合Monolog库实现错误记录。以Laravel和Symfony为例,可在配置文件中定义多通道(如文件、Slack)、设置不同级别(ERROR、CRITICAL),并通过门面或服务在代码中捕获异常并写入上下文信息。 PHP框架的日志系统记录错误,核心在于通…

    2026年9月22日
    000
  • Laravel 8 注册成功但登录失败的解决方案

    本文针对 Laravel 8 中使用 php artisan ui:auth 生成的认证系统,注册功能正常但登录功能失效的问题,提供了一种解决方案。通过重写 LoginController 中的 username() 方法,将认证字段从默认的 email 修改为 username,从而解决登录失败的…

    2026年9月22日
    200
  • laravel+redis有哪些用法

    laravel+redis有用法有:1、使用Redis作为缓存驱动器;2、使用Laravel提供的缓存操作方法来操作Redis缓存;3、使用Redis作为数据存储系统,Laravel提供了与Redis交互的方法,使我们能够方便地进行数据存储和读取;4、还提供了其他高级功能,如发布订阅、事务和管道等,…

    2026年9月22日
    700
  • laravel路由错误怎么办

    laravel路由错误解决方法:1、检查路由定义是否正确,如果错误,根据错误提示进行修改;2、检查路由命名冲突,可以修改其中一个路由的名称来解决冲突;3、清除路由缓存,使用“php artisan route:clear”命令来清除路由缓存;4、检查路由参数,可以在路由定义中使用正则表达式来限制参数…

    2026年9月22日
    1400
  • 使用空值合并运算符为数组元素设置默认值

    本文将介绍如何使用 PHP 的空值合并运算符 (??) 为数组元素设置默认值,尤其是在处理用户输入时。 通过该运算符,可以在变量值为 null 或不存在时,提供一个备选值,从而简化代码并提高可读性。我们将通过一个实际的 Laravel 邮件发送示例,演示如何在请求参数中缺失主题时,设置默认主题。 空…

    2026年9月22日
    600
  • laravel表单类用法是什么

    laravel表单类用法有:1、表单验证,提供了一种简单而强大的方式来验证表单数据,可以使用validate方法来定义验证规则和错误消息;2、表单重填,提供了一个方便的方式来重新填充表单字段的值,可以使用old方法来获取上一次提交的值;3、文件上传,提供了一个方便的方式来处理文件上传,可以在表单中添…

    2026年9月22日
    500
  • laravel Spatie/laravel-medialibrary包高级用法_Laravel Spatie Medialibrary高级功能使用方法

    Spatie/laravel-medialibrary 支持自定义磁盘路径、响应式图像、WebP格式、媒体集合分类、自定义属性存储及签名URL安全访问,并可通过队列异步处理文件转换,提升性能与安全性。 在 Laravel 应用中,Spatie/laravel-medialibrary 是处理文件上传…

    2026年9月22日
    1300
  • PHP中为数组元素设置默认值的最佳实践:使用Null合并运算符

    本教程将介绍如何在PHP中为数组元素设置默认值,尤其当源数据可能为空或缺失时。通过利用PHP 7+提供的Null合并运算符(??),可以简洁高效地实现这一需求,避免冗长的条件判断,提高代码可读性和健壮性。 引言:处理缺失或空值时的数组赋值 在Web开发中,我们经常需要从用户请求、数据库查询或其他外部…

    2026年9月22日
    100
  • Laravel 8 登录后重定向至仪表盘的策略与实践

    本教程详细阐述了在 Laravel 8 中实现用户登录后重定向到仪表盘的多种策略。我们将探讨如何通过配置 LoginController 的 $redirectTo 属性、利用 RouteServiceProvider 定义常量以及在自定义登录方法中进行精确控制来管理重定向流程。文章还涵盖了相关中间…

    2026年9月22日
    100
  • laravel中的契约(Contracts)和门面(Facades)有什么关系_Laravel契约与门面关系解析

    Laravel中的契约定义服务接口,门面提供静态代理,二者协同实现松耦合与易用性:契约通过依赖注入保障可测试性与类型安全,门面通过静态调用简化语法,实际底层对象通常实现对应契约,如Cache门面代理实现IlluminateContractsCacheRepository接口的实例,两者可依场景灵活选…

    2026年9月22日
    100
  • Laravel 8 登录后重定向到仪表盘:完整教程

    本教程详细阐述了在 Laravel 8 中实现用户登录后重定向到仪表盘的多种方法。我们将探讨 Laravel 默认的重定向机制、如何正确配置仪表盘路由及其中间件,并提供通过自定义 LoginController 实现精确重定向的示例代码。通过本文,您将全面掌握 Laravel 认证后的重定向流程,并…

    2026年9月22日
    500
  • MySQL字段注释快速补全方法_Sublime脚本自动生成标准文档结构

    MySQL字段注释快速补全方法_Sublime脚本自动生成标准文档结构MySQL字段注释快速补全方法_Sublime脚本自动生成标准文档结构MySQL字段注释快速补全方法_Sublime脚本自动生成标准文档结构MySQL字段注释快速补全方法_Sublime脚本自动生成标准文档结构

    要快速补全mysql字段注释,可通过sublime text编写python脚本实现自动化;1. 脚本获取表名,可手动输入或从当前sql文件解析;2. 通过subprocess调用mysql命令行获取show full columns信息;3. 解析输出内容,提取字段名和现有注释;4. 生成alte…

    2026年9月21日 用户投稿
    300
  • laravel集合有where方法吗

    有。Laravel集合中的where方法是一个非常有用的方法,用于在集合中筛选元素,根据指定的条件返回匹配的元素。使用where方法,可以根据不同的条件来过滤集合中的元素,where方法接受一个闭包作为参数,闭包中可以定义筛选的条件,闭包的每个元素都会传递给闭包。无论是对关联数组还是对对象集合,wh…

    2026年9月21日
    100
  • laravel如何判断请求类型

    laravel判断请求类型的方法:1、使用Request对象的方法,在Laravel中,每个请求都会通过Request对象进行处理。Request对象提供了一些有用的方法来判断请求类型;2、使用路由方法,在Laravel中,路由文件定义了应用程序的请求路由,可以使用路由方法来判断请求类型;3、使用中…

    2026年9月21日
    200
  • Laravel 8 登录后重定向到仪表盘的完整教程

    本教程详细介绍了在 Laravel 8 中实现用户登录后重定向到仪表盘的多种方法。我们将探讨如何利用 Laravel 内置的 $redirectTo 属性,以及如何通过重写 LoginController 中的 login 方法来实现自定义重定向逻辑。此外,教程还将重点讲解正确的路由配置和中间件使用…

    2026年9月21日
    100
  • laravel怎么监控错误

    laravel监控错误的方法:1、错误日志记录,Laravel内置了一个非常强大的日志系统,可以通过查看这些日志文件来了解应用程序中发生的错误;2、异常处理,Laravel提供了一个Exception类,可以用来捕获和处理异常;3、自定义错误页面,创建不同的视图文件,用于处理特定类型错误,当发生相应…

    2026年9月21日
    200

发表回复

登录后才能评论
关注微信