Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Laravel command

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use the Laravel command". In the daily operation, I believe that many people have doubts about how to use the Laravel command. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the Laravel command". Next, please follow the editor to study!

Laravel quick look-up table

Project command

/ / create a new project $laravel new projectName// run Service / Project $php artisan serve// View instruction list $php artisan list// help $php artisan help migrate// Laravel console $php artisan tinker// View Route list $php artisan route:list

Public instruction

/ / Database migration $php artisan migrate// data fill $php artisan db:seed// create data table migration file $php artisan make:migration create_products_table// generation model options: / /-m (migration),-c (controller),-r (resource controllers),-f (factory) -s (seed) $php artisan make:model Product-mcf// generation controller $php artisan make:controller ProductsController// table update field $php artisan make:migration add_date_to_blogposts_table// rollback last migration php artisan migrate:rollback// rollback all migrations php artisan migrate:reset// rollback all migrations and refresh php artisan migrate:refresh// rollback all migrations Refresh and generate data php artisan migrate:refresh-seed

Create and update data tables

/ / create data table $php artisan make:migration create_products_table// create data table (migration example) Schema::create ('products', function (Blueprint $table) {/ / add primary key $table- > id (); / / created_at and updated_at fields $table- > timestamps (); / / unique constraint $table- > string (' modelNo')-> unique () / / unnecessary $table- > text ('description')-> nullable (); / / default value $table- > boolean (' isActive')-> default (true); / / Index $table- > index (['account_id',' created_at']); / / Foreign key constraint $table- > foreignId ('user_id')-> constrained (' users')-> onDelete ('cascade');}) / / update table (migration example) $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');})

Model

/ / Model quality specified list excludes attributes protected $guarded = []; / / empty = = All// or list containing attributes protected $fillable = ['name',' email', 'password',]; / / one-to-many relationship (one post corresponds to multiple comments) public function comments () {return $this- > hasMany (Comment:class) } / / one-to-many relationship (multiple comments under one post) public function post () {return $this- > belongTo (Post::class);} / / one-to-one relationship (author and profile) public function profile () {return $this- > hasOne (Profile::class) } / / one-to-one relationship (profile and author) public function author () {return $this- > belongTo (Author::class) } / / many-to-many relationship / / 3 tables (posts, tags and posts-tags) / / posts-tags: post_tag (post_id, tag_id) / / in the "tag" model. Public function posts () {return $this- > belongsToMany (Post::class);} / / in the post model. Public function tags () {return $this- > belongsToMany (Tag::class);}

Factory

/ / example: database/factories/ProductFactory.phppublic function definition () {return ['name' = > $this- > faker- > text (20),' price' = > $this- > faker- > numberBetween (10, 10000),];} / all fakers options: https://github.com/fzaninotto/Faker

Seed

/ / example: database/seeders/DatabaseSeeder.phppublic function run () {Product::factory (10)-> create ();}

Run Seeders

Execute $php artisan migrate-- seed when $php artisan db:seed// or migration

Eloquent ORM

/ / New $flight = new Flight;$flight- > name = $request- > name;$flight- > save (); / / Update $flight = Flight::find (1); $flight- > name = 'New Flight Name';$flight- > save (); / / create $user = User::create ([' first_name' = > 'Taylor','last_name' = >' Otwell']); / / Update all: Flight::where ('active', 1)-> update ([' delayed' = > 1]) / / delete $current_user = User::Find (1) $current_user.delete (); / / delete all $deletedRows = Flight::where ('active', 0)-> delete () according to id: User::destroy (1); / / get all $items = Item::all (). / / query a record according to the primary key $flight = Flight::find (1); / / if it does not exist, display $model = Flight::findOrFail (1); / / get the last record $items = Item::latest ()-> get () / / chain $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'))

Routin

/ / basic closure routing Route::get ('/ greeting', function () {return 'Hello World';}); / / View routing shortcut Route::view (' / welcome', 'welcome'); / / routing to controller use App\ Http\ Controllers\ UserController;Route::get (' / user', [UserController::class, 'index']) / / routing Route::match for specific HTTP verbs only (['get',' post'],'/', function () {/ /}); / / routing Route::any ('/', function () {/ /}) responding to all HTTP requests; / / redirecting routing Route::redirect ('/ clients','/ customers') / / routing parameter Route::get ('/ user/ {id}', function ($id) {return 'User'. $id;}); / / optional parameter Route::get ('/ user/ {name?}', function ($name = 'John') {return $name;}); / / Route naming Route::get (' / user/profile', [UserProfileController::class, 'show'])-> name (' profile') / / Resource routing 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// full Resource routing Route::resource (' photos.comments', PhotoCommentController::class) / / partial resource routing Route::resource ('photos', PhotoController::class)-> only ([' index', 'show']); Route::resource (' photos', PhotoController::class)-> except (['create',' store', 'update',' destroy']); / / generate URL$url = route using the route name ('profile', [' id' = > 1]) / / generate redirection... return redirect ()-> route ('profile'); / / routing group prefix Route::prefix (' admin')-> group (function () {Route::get ('/ users', function () {/ / Matches The "/ admin/users" URL});}); / / routing model binding use App\ Models\ User;Route::get ('/ users/ {user}', function (User $user) {return $user- > email) }); / / routing model binding (except id) use App\ Models\ User;Route::get ('/ posts/ {post:slug}', function (Post $post) {return view ('post', [' post' = > $post]);}); / / alternative route Route::fallback (function () {/ /})

Caching

/ / routing cache php artisan route:cache// gets or saves (key, time to live, value) $users = Cache::remember ('users', now ()-> addMinutes (5), function () {return DB::table (' users')-> get ();})

Controller

/ / set protected $rules = ['title' = >' required | unique:posts | max:255', 'name' = >' required | min:6', 'email' = >' required | email', 'publish_at' = >' nullable | date',]; / / check $validatedData = $request- > validate ($rules) / / display abort (404, 'Sorry, Post not found') / / Controller CRUD example 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')) } / / Model injection method 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") }} / / get Query Params www.demo.html?name=mikerequest ()-> name / / mike// get Form data pass parameter (or default) 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 twodies'@ 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')}}

Access the database without using the model

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 = 1mm, ['eric']); DB::delete (' delete from users where id = 1')

Helper function

/ / display the contents of the variable and terminate the execution of dd ($products) / / convert the array to the Laravel collection $collection = collect ($array); / / sort $ordered_collection = $collection- > orderBy ('description') by description ascending order; / / reset the collection key $ordered_collection = $ordered_collection- > values ()-> all (); / / return the full path of the project app\: app_path (); resources\: resource_path (); database\: database_path ()

Flash memory and Session

/ / Flash (next request only) $request- > session ()-> flash ('status',' Task was reserved fulfillment'); / / Flash return redirect with redirection ('/ home')-> with ('success' = >' email sentencing'); / / set Session$request- > session ()-> put ('key',' value'); / / get session$value = session ('key') If session: if ($request- > session ()-> has ('users')) / / Delete session$request- > session ()-> forget (' key'); / / display flash@if (session ('message')) {{session (' message')}} @ endif in the template

HTTP Client

/ / introduce package use Illuminate\ Support\ Facades\ Http;// Http get request $response = Http::get ('www.thecat.com') $data = $response- > json () / / Http get request with parameter $res = Http::get (' www.thecat.com', ['param1',' param2']) / / Http post request with request body $res = Http::post ('http://test.com', [' name' = > 'Steve','role' = >' Admin']) / / request $res = Http::withToken ('123456789')-> post ('http://the.com', [' name' = > 'Steve']); / / request $res = Http::withHeaders ([' type'= > 'json'])-> post (' http://the.com', ['name' = >' Steve'])

Storage (helper class for storing local files or cloud services)

/ / Public driver configuration: Local storage/app/publicStorage::disk ('public')-> exists (' file.jpg')) / / S3 cloud storage driver configuration: storage: for example, Amazon Cloud: Storage::disk ('s3')-> exists (' file.jpg')) / / expose public access content in the web service php artisan storage:link// gets or saves the file use Illuminate\ Support\ Facades\ Storage in the storage folder Storage::disk ('public')-> put (' example.txt', 'Contents'); $contents = Storage::disk (' public')-> get ('file.jpg'); / / by generating url $url = Storage::url (' file.jpg') to access the resource; / / or the absolute path through the public configuration

/ / delete the file Storage::delete ('file.jpg'); / / download the file Storage::disk (' public')-> download ('export.csv')

Install a new project from 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 deployment

/ / Local (MacOs) machine installs Heroku $brew tap heroku/brew & & brew install heroku// login heroku (if it does not exist) $heroku login// creates Profile $touch Profile// saves Profileweb: vendor/bin/heroku-php-apache2 public/Rest API (create Rest API endpoint)

API routes (all api routes are prefixed with '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 resources (the resource layer between the model and the JSON response)

$php artisan make:resource ProductResource

Resource routing definition file

/ / app/resource/ProductResource.phppublic function toArray ($request) {return ['id' = > $this- > id,' name' = > $this- > name, 'price' = > $this- > price,' custom' = > 'This is a custom field',];}

API controller (best practice is to put your API controller in 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 authentication

First, you need to create a Token for a specific user. [related recommendations: the latest five Laravel video tutorials]

$user = User::first (); $user- > createToken ('dev token'); / / plainTextToken: "1 | v39On3Uvwl0yA4vex0f9SgOk3pVdLECDk4Edi4OJ"

Then you can use this token with a request.

GET api/products (Auth Bearer Token: plainTextToken)

Authorization rules

You can create tokens using predefined authorization rules

$user- > createToken ('dev token', [' product-list']); / / in controllersif! auth ()-> user ()-> tokenCan ('product-list') {abort (403, "Unauthorized");} at this point, the study on "how to use the Laravel command" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report