這篇文章主要介紹“怎么使用Laravel命令”,在日常操作中,相信很多人在怎么使用Laravel命令問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用Laravel命令”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
目前成都創(chuàng)新互聯(lián)已為千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬空間、網(wǎng)站托管運(yùn)營、企業(yè)網(wǎng)站設(shè)計、清徐網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
Laravel 速查表
項目命令
// 創(chuàng)建新項目 $ laravel new projectName // 運(yùn)行 服務(wù)/項目 $ php artisan serve // 查看指令列表 $ php artisan list // 幫助 $ php artisan help migrate // Laravel 控制臺 $ php artisan tinker // 查看路由列表 $ php artisan route:list
公共指令
// 數(shù)據(jù)庫遷移 $ php artisan migrate // 數(shù)據(jù)填充 $ php artisan db:seed // 創(chuàng)建數(shù)據(jù)表遷移文件 $ 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 // 回滾所有遷移,刷新并生成數(shù)據(jù) php artisan migrate:refresh --seed
創(chuàng)建和更新數(shù)據(jù)表
// 創(chuàng)建數(shù)據(jù)表 $ php artisan make:migration create_products_table // 創(chuàng)建數(shù)據(jù)表(遷移示例) Schema::create('products', function (Blueprint $table) { // 自增主鍵 $table->id(); // created_at 和 updated_at 字段 $table->timestamps(); // 唯一約束 $table->string('modelNo')->unique(); // 非必要 $table->text('description')->nullable(); // 默認(rèn)值 $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'); });
模型
// 模型質(zhì)量指定列表排除屬性 protected $guarded = []; // empty == All // 或者包含屬性的列表 protected $fillable = ['name', 'email', 'password',]; // 一對多關(guān)系 (一條帖子對應(yīng)多條評論) public function comments() { return $this->hasMany(Comment:class); } // 一對多關(guān)系 (多條評論在一條帖子下) public function post() { return $this->belongTo(Post::class); } // 一對一關(guān)系 (作者和個人簡介) public function profile() { return $this->hasOne(Profile::class); } // 一對一關(guān)系 (個人簡介和作者) public function author() { return $this->belongTo(Author::class); } // 多對多關(guān)系 // 3 張表 (帖子, 標(biāo)簽和帖子-標(biāo)簽) // 帖子-標(biāo)簽:post_tag (post_id, tag_id) // 「標(biāo)簽」模型中... 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/Faker
Seed
// 例子: database/seeders/DatabaseSeeder.php public function run() { Product::factory(10)->create(); }
運(yùn)行 Seeders
$ php artisan db:seed // 或者 migration 時執(zhí)行 $ 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(); // 創(chuàng)建 $user = User::create(['first_name' => 'Taylor','last_name' => 'Otwell']); // 更新所有: Flight::where('active', 1)->update(['delayed' => 1]); // 刪除 $current_user = User::Find(1) $current_user.delete(); // 根據(jù) id 刪除: User::destroy(1); // 刪除所有 $deletedRows = Flight::where('active', 0)->delete(); // 獲取所有 $items = Item::all(). // 根據(jù)主鍵查詢一條記錄 $flight = Flight::find(1); // 如果不存在顯示 404 $model = Flight::findOrFail(1); // 獲取最后一條記錄 $items = Item::latest()->get() // 鏈?zhǔn)?nbsp; $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'))
路由
// 基礎(chǔ)閉包路由 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 () { // }); // 響應(yīng)所有 HTTP 請求的路由 Route::any('/', function () { // }); // 重定向路由 Route::redirect('/clients', '/customers'); // 路由參數(shù) Route::get('/user/{id}', function ($id) { return 'User '.$id; }); // 可選參數(shù) 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(); });
控制器
// 設(shè)置校驗規(guī)則 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 傳參(或默認(rèn)值) 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
不使用模型訪問數(shù)據(jù)庫
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');
幫助函數(shù)
// 顯示變量內(nèi)容并終止執(zhí)行 dd($products) // 將數(shù)組轉(zhuǎn)為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!'); // 設(shè)置 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']); // 帶令牌認(rèn)證方式請求 $res = Http::withToken('123456789')->post('http://the.com', ['name' => 'Steve']); // 帶請求頭方式發(fā)起請求 $res = Http::withHeaders(['type'=>'json'])->post('http://the.com', ['name' => 'Steve']);
Storage (用于存儲在本地文件或者云端服務(wù)的助手類)
// Public 驅(qū)動配置: Local storage/app/public Storage::disk('public')->exists('file.jpg')) // S3 云存儲驅(qū)動配置: storage: 例如 亞馬遜云: Storage::disk('s3')->exists('file.jpg')) // 在 web 服務(wù)中暴露公共訪問內(nèi)容 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'); // 或者通過公共配置的絕對路徑// 刪除文件 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)機(jī)器安裝 Heroku $ brew tap heroku/brew && brew install heroku // 登陸 heroku (不存在則創(chuàng)建) $ heroku login // 創(chuàng)建 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 響應(yīng)之間的資源層)
$ 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 控制器 (最佳實(shí)踐是將您的 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); }
首先,您需要為特定用戶創(chuàng)建一個 Token?!鞠嚓P(guān)推薦:最新的五個Laravel視頻教程】
$user = User::first(); $user->createToken('dev token'); // plainTextToken: "1|v39On3Uvwl0yA4vex0f9SgOk3pVdLECDk4Edi4OJ"
然后可以一個請求使用這個令牌
GET api/products (Auth Bearer Token: plainTextToken)
授權(quán)規(guī)則
您可以使用預(yù)定義的授權(quán)規(guī)則創(chuàng)建令牌
$user->createToken('dev token', ['product-list']); // in controllers if !auth()->user()->tokenCan('product-list') { abort(403, "Unauthorized"); }
到此,關(guān)于“怎么使用Laravel命令”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!