新鲜出炉的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

相关推荐

  • composer require-dev和require有什么不同_Composer Require与Require-Dev区别解析

    require用于声明项目运行必需的依赖,如框架、数据库组件和第三方SDK,这些包会随项目部署到生产环境;2. require-dev用于声明仅在开发和测试阶段需要的工具,如PHPUnit、PHPStan、Faker等,不会默认部署到生产环境;3. 安装时composer install根据环境决定…

    2026年5月10日
    1000
  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • 深入理解 Laravel Session::put:避免常见陷阱与实现表单限流

    本文旨在深入探讨 laravel 框架中 `session::put` 方法的正确用法及其常见误区。针对用户在实现表单提交限流时遇到的问题,详细阐述了 `session::put` 必须提供键值对的原理,并提供了如何在控制器中利用会话机制有效防止重复提交的实战代码示例。通过本文,读者将掌握 lara…

    2026年5月10日
    000
  • Voyager 中关联关系的翻译问题解决方案

    本文档旨在解决在使用 TCGVoyager 管理后台时,关联模型无法正确翻译的问题。主要针对 Laravel 项目中,使用 Voyager 1.4 版本以及 Laravel 8.0 版本,并且已经配置多语言支持的情况下,如何确保关联关系中的可翻译字段能够根据当前应用语言环境进行正确翻译。通过修改 B…

    2026年5月10日
    000
  • 优化 Laravel Eloquent 查询:高效构建用户排行榜数据

    本教程详细讲解如何优化 Laravel Eloquent 查询以高效生成基于关联记录计数的排行榜。通过识别并消除冗余的 whereHas 子句,并巧妙利用 withCount 的条件闭包,我们能显著提升查询性能,大幅缩短数据获取时间,从而改善用户体验并降低数据库负载。 在 laravel 应用开发中…

    2026年5月10日
    000
  • 告别重复:使用Laravel Precognition统一前后端API验证

    本文旨在解决在Laravel后端与前端API交互中,如何高效复用后端验证规则的挑战。传统方案常限于表单元素,难以覆盖所有API请求。通过引入Laravel Precognition,开发者能够实现后端验证逻辑在前端的无缝应用,避免规则重复编写,从而提升开发效率与代码一致性,确保所有API请求的数据完…

    2026年5月10日
    200
  • Laravel Session::put 正确用法详解与常见误区规避

    本文详细探讨了 laravel 中 `session::put` 方法的正确用法,特别指出在仅提供键名而未指定值时可能导致会话数据未被正确设置的问题。通过示例代码,阐述了如何为会话数据赋予明确的值,并演示了如何正确地检查和获取会话数据,以确保会话管理功能按预期工作,有效避免常见的会话操作错误。 La…

    2026年5月10日
    000
  • PHP中批量为嵌套数组元素添加公共属性的教程

    本教程将详细介绍在php中如何高效地为包含多个关联数组的集合中的每个子数组添加一个或多个新的公共键值对。我们将探讨使用循环和数组合并函数实现这一目标的方法,并提供清晰的代码示例,帮助开发者处理此类数据结构转换。 在PHP开发中,我们经常会遇到处理复杂数据结构的需求,其中一种常见场景是拥有一个由多个关…

    2026年5月10日
    000
  • PHP框架的社区支持存在哪些痛点?

    php框架社区支持的痛点包括:文档匮乏或过时(1)、响应缓慢(2)、社区分散(3)。实战案例表明这些痛点可能导致开发进度受阻。改善方法包括:提供全面的文档、建立响应迅速的官方论坛、创建一个集成的社区平台。 PHP 框架社区支持存在的痛点及实战案例 PHP 框架为 Web 开发提供了强大的基础,但其社…

    2026年5月10日
    100
  • Laravel 8中Firebase Storage文件条件删除策略与实践

    本文针对Laravel 8环境下Firebase Storage无法直接按目录批量或条件删除文件的限制,提出了一套基于元数据管理的解决方案。通过在数据库中记录文件信息,结合Laravel的Artisan命令和Cron任务,实现对过期文件的精准识别与逐个删除,确保存储资源的有效管理。 Firebase…

    2026年5月10日
    000
  • php怎么安装_在云服务器上部署PHP环境的步骤

    答案:在云服务器上部署PHP环境需搭建LEMP栈(Linux+Nginx+MySQL+PHP-FPM),依次更新系统、安装Nginx、MariaDB、PHP-FPM及扩展,配置Nginx解析PHP并测试,最后通过权限控制、安全配置、防火墙和HTTPS等措施保障环境安全稳定。 在云服务器上部署PHP环…

    2026年5月10日
    000
  • Laravel 产品多图上传错误:foreach() 参数类型问题解决方案

    本文旨在解决 Laravel 应用中产品多图上传时遇到的 “foreach() argument must be of type array|object, null given” 错误。通过检查并确保循环遍历的变量为数组类型,避免因空值导致的错误,并提供代码示例和注意事项,…

    2026年5月10日
    200
  • PHP源码命令行工具开发_PHP源码命令行工具开发教程

    答案是使用PHP开发命令行工具需依托CLI SAPI,结合Composer管理依赖,并推荐采用Symfony Console等组件库来构建。首先确保PHP支持CLI模式,通过编写基础脚本并利用$argv和getopt()处理参数,但更优方式是引入Symfony Console组件进行命令定义与输入输…

    2026年5月10日
    000
  • PHP怎么运行创建_php脚本创建与执行流程解析

    PHP脚本需在服务器环境中通过解释器运行,不能双击执行。首先搭建环境(如XAMPP),然后编写.php文件并保存至服务器根目录,接着通过浏览器访问或命令行执行php命令运行脚本,服务器会调用PHP解释器解析代码并返回结果。 PHP脚本的运行依赖于服务器环境和解释器,不是直接像可执行程序那样双击运行。…

    2026年5月10日
    100
  • php中get_parent_class获取父类名_php在继承链中定位父类的应用场景

    get_parent_class函数用于获取类的父类名称,接收类名字符串返回父类名或false。示例中Dog类继承Animal,调用get_parent_class(__CLASS__)输出Animal。应用场景一:条件性调用父类方法,如构造函数中判断是否存在父类并调用其方法,提升灵活性。应用场景二…

    2026年5月10日
    100
  • 使用Laravel Blade动态渲染带标题的表格数据

    本文旨在详细指导如何在Laravel Blade模板中,利用`@foreach`循环和正确的索引策略,高效且准确地从嵌套数组结构中提取数据,并将其渲染成一个结构清晰、内容匹配的HTML表格,避免数据重复和错位问题。 在Web开发中,经常需要根据后端提供的数据动态生成HTML表格。特别是在处理具有行标…

    2026年5月10日
    000
  • Laravel模型中实现多语言数据自动过滤:重写newQuery()方法

    本教程详细介绍在laravel多语言应用中,如何通过重写模型(model)的`newquery()`方法,实现数据查询时自动根据当前应用语言环境进行过滤。这种方法提供了一种优雅且dry(don’t repeat yourself)的解决方案,避免了在每次数据查询时手动添加语言条件,确保了…

    2026年5月10日
    000
  • php学习有哪些

    PHP 学习途径:入门途径:在线教程:Codecademy、Udemy、Coursera 等书籍:《Head First PHP & MySQL》、《PHP in Action》官方文档:PHP 官方文档进阶学习:框架:Laravel、CodeIgniter 等数据库:MySQL、Postg…

    2026年5月10日
    100
  • 在 Laravel 中同时存储原始图片和 WebP 转换图片

    本文详细介绍了在 Laravel 应用中如何高效地处理图片上传,实现同时保存原始图片(如 JPG/PNG)及其 WebP 转换版本。通过利用 PHP 原生 GD 库功能,我们能够克服 Intervention Image 在特定场景下的路径写入问题,确保原始图片和优化后的 WebP 格式文件都能正确…

    2026年5月10日
    000
  • 解决AJAX响应中PHP输出JSON后出现多余HTML的问题

    本文旨在解决PHP脚本通过AJAX响应返回JSON数据时,出现JSON数据后方意外附带HTML内容的问题。通过在PHP脚本中JSON编码输出后立即使用die()或exit()函数,可以有效阻止后续不必要的输出,确保客户端接收到纯净、可解析的JSON响应,从而避免解析错误,提升前后端通信的健壮性。 理…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信