下面由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);}
原文地址:https://dev.to/ericchapman/my-beloved-laravel-cheat-sheet-3l73
译文地址:https://learnku.com/laravel/t/62150
以上就是新鲜出炉的laravel 速查表不要错过!的详细内容。