Laravel 13的新特性有哪些?

PHP wes 20 days ago (2026-04-09) 147 views

        Laravel 13 最低的PHP版本要求是PHP 8.3,全新代码更轻量、更快速。它是一套完整的开发生态:内置路由、ORM、认证、队列、缓存、邮件、任务调度等全套功能,开箱即用、零配置启动,新手能快速上手,老手能高效交付,同时深度适配 AI 时代,让普通开发者也能轻松做智能应用。本文汇总了Laravel 13 中令人印象深刻的核心新特性。3y4.net

一、AI 功能(软件开发必备)

use Laravel\AI\Facades\AI; $result = AI::text() ->prompt('用通俗语言介绍 Laravel 13') ->generate(); $embedding = AI::embedding()->create($article->content); $agent = AI::agent()->tools([ \App\AI\Tools\OrderTool::class, ]); $answer = $agent->prompt('查一下订单 1001 的状态')->run();

二、向量相似度搜索(语义搜索)

 $similar = DB::table('articles') ->whereVectorSimilarTo('embedding', 'Laravel 新特性') ->limit(10) ->get();

三、PHP 属性路由(新版推荐写法)

use Laravel\Routing\Attributes\Get; use Laravel\Routing\Attributes\Middleware; use Laravel\Routing\Attributes\Authorize; class PostController { #[Get('/posts/{post}')] #[Middleware('auth')] #[Authorize('view', Post::class)] public function show(Post $post) { return view('post.show', compact('post')); } }

四、JSON:API 标准资源(前后端分离必备)

use Laravel\JsonApi\JsonApiResource; class PostResource extends JsonApiResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, ]; } public function includes() { return ['user', 'comments']; } } Route::get('/api/posts/{post}', fn (Post $post) => new PostResource($post));

五、秒级限流(更精细的接口防护)

use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Support\Facades\RateLimiter; RateLimiter::for('api', function ($request) { return Limit::perSecond(5)->by($request->ip()); });

六、队列任务属性(更简洁)

use Laravel\Queue\Attributes\Tries; use Laravel\Queue\Attributes\Backoff; use Laravel\Queue\Attributes\Queue; #[Tries(3)] #[Backoff(100, 200, 500)] #[Queue('heavy')] class ProcessVideo implements ShouldQueue { public function handle() { ... } }

七、极简路由(Laravel 11/12/13 通用)

Route::get('/', fn () => view('welcome')); Route::view('/about', 'about'); Route::resource('posts', PostController::class)->only(['index', 'show']);

八、Eloquent ORM 常用示例

 Post::with('user', 'comments')->latest()->paginate(10); Post::where('is_published', true) ->whereMonth('created_at', date('m')) ->get(); public function user() { return $this->belongsTo(User::class); }

九、Blade 模板常用语法

@extends('layout.app') @section('content') <h1>{{ $post->title }}</h1> @if($post->comments->count()) @foreach($post->comments as $c) <div>{{ $c->content }}</div> @endforeach @else <p>暂无评论</p> @endif @endsection

十、常用 Artisan 命令

# 创建控制器
php artisan make:controller PostController # 创建模型 + 迁移 php artisan make:model Post -m # 创建资源控制器 php artisan make:controller PostController --resource # 执行迁移 php artisan migrate # 启动服务 php artisan serve