您好,登录后才能下订单哦!
这篇文章主要介绍“怎么使用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.php
public function definition() {
    return [
        'name' => $this->faker->text(20),
        'price' => $this->faker->numberBetween(10, 10000),
    ];
}
// 所有 fakers 选项 : https://github.com/fzaninotto/FakerSeed
// 例子: database/seeders/DatabaseSeeder.php
public 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();
// Where
Todo::where('id', $id)->firstOrFail()  
// Like 
Todos::where('name', 'like', '%' . $my . '%')->get()
// Or where
Todos::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.index
GET /photos/create  create  photos.create
POST    /photos store   photos.store
GET /photos/{photo} show    photos.show
GET /photos/{photo}/edit    edit    photos.edit
PUT/PATCH   /photos/{photo} update  photos.update
DELETE  /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=mike
request()->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') }} @endifHTTP 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/public
Storage::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 installHeroku 部署
// 本地(MacOs)机器安装 Heroku $ brew tap heroku/brew && brew install heroku // 登陆 heroku (不存在则创建) $ heroku login // 创建 Profile $ touch Profile // 保存 Profile web: vendor/bin/heroku-php-apache2 public/
API 路由 ( 所有 api 路由都带 'api/' 前缀 )
// routes/api.php
Route::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.php
public 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);
    }首先,您需要为特定用户创建一个 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 controllers
if !auth()->user()->tokenCan('product-list') {
    abort(403, "Unauthorized");
}到此,关于“怎么使用Laravel命令”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。