Write it up front

I got in touch with Laravel because of a project opportunity. Since I have been using ThinkPHP before, I found that the two are very similar, at least it is easier to get started. Here I record the knowledge points and pits I have encountered in the production, hoping to help friends in need. Thank you, hahaha!

Laravel8 official Chinese document

  • The homepage learnku.com/docs/larave…
  • Controller – Resource Controller operation processing learnku.com/docs/larave…
  • Model learnku.com/docs/larave…
  • Model association learnku.com/docs/larave…
  • Form validation learnku.com/docs/larave…
  • Database Migration – Available field types learnku.com/docs/larave…
  • BladeThe templateLearnku.com/docs/larave…

The mirror

Composer config - g repo. Packagist composer https://mirrors.aliyun.com/composer/ (ali cloud) composer config - g repo. Packagist Composer https://packagist.phpcomposer.com (original)Copy the code

Immediately began to

  1. ComposerThe installationhttps://getcomposer.org/download/
  2. First Global Installationlaravelinstallercomposer global require laravel/installer
  3. The installationComposer create-project --prefer-dist Laravel/Laravel project name
  4. runphp artisan serve

Local IP ARTISan Serve –host=192.168.1.7 if you want to work with LAN shared access. The actual access address is http://192.168.1.7:8000


The controller

  1. ordinaryphp artisan make:controller Home
  2. resourcesphp artisan make:controller Home --resource
  3. API php artisan make:controller api/Home --api

routing

  1. ordinaryroutes/web.php
use App\Http\Controllers\Home;
Route::get('/', [Home::class, 'index']);
Copy the code
  1. resourcesroutes/web.php
use App\Http\Controllers\Home;
Route::resource('/', Home::class);
Copy the code
  1. API routes/api.php
use App\Http\Controllers\api\JsonList;
Route::apiResource('json_list', JsonList::class);
Copy the code

View all registered routes PHP artisan Route :list

Routing group
  • A single
Route::middleware(['auth'])->group(function () {
    Route::resource('/store', App\Http\Controllers\Store::class);
    Route::resource('/wine', App\Http\Controllers\Wine::class);
});
Copy the code
  • multiple
Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function () {
    Route::resource('/store', App\Http\Controllers\Store::class);
    Route::resource('/wine', App\Http\Controllers\Wine::class);
});
Copy the code

The database

  1. The new tablephp artisan make:migration create_users_table
  2. Sync to databasephp artisan migrate

model

  • php artisan make:model List
  • Fields can be written, otherwise they cannot be addedapp/Models/List.phpaddprotected $fillable = ['name','address'];
  • Enabling Soft Deleteapp/Models/List.phpadd
use Illuminate\Database\Eloquent\SoftDeletes; {/ /... use SoftDeletes; }Copy the code
  • Timestamp pure digitsapp/Models/List.phpaddprotected $dateFormat = 'U';
  • modifierapp/Models/List.php
public function get***Attribute($value) { $this->id; // Call id field return $value; // Final output}Copy the code
Use the model in the controller
  • The introduction of
use App\Models\Store as ModelStore;
Copy the code
  • Paging all data
$stores = ModelStore::orderBy('id', 'desc')->paginate(10);
return view('store.index', ['stores' => $stores]);
Copy the code
Associated query
  • model
class WineAward extends Model { use HasFactory; public function wxuser() { return $this->belongsTo('App\Models\WxUser'); } public function wine() { return $this->belongsTo('App\Models\Wine'); }}Copy the code
  • Controller output
$wineaward = ModelWineAward::find($id)->with(['wxuser','wine'])->get();
Copy the code
  • The controller specifies content output
$wineaward = ModelWineAward::find($id)->with(['wxuser:id,nickname','wine:id,name'])->get();
Copy the code
Nested associated query

Select WineAward from wine() and then query the Store of Wine controller ().

// WineAward.php
wine.store
Copy the code
  • modelWineAward
class WineAward extends Model { use HasFactory; public function wxuser() { return $this->belongsTo('App\Models\WxUser'); } public function wine() { return $this->belongsTo('App\Models\Wine'); }}Copy the code
  • modelWine
class Wine extends Model { use HasFactory; public function store() { return $this->belongsTo('App\Models\Store'); }}Copy the code
  • Controller output
$wineaward = ModelWineAward::find($id)->with(['wxuser:id,nickname','wine:id,name,store_id','wine.store:id,name'])->get();
Copy the code

empty

  1. php artisan config:clear

A collection of

Collection – An encapsulation of array data

Learnku.com/docs/larave…

Laravel Jetstream

Integrate user login and registration, according to official documents, no big problem.

Jetstream.laravel.com/2.x/introdu… Learnku.com/docs/larave…

The installation
  1. The installationcomposer require laravel/jetstream
  2. Personal editionphp artisan jetstream:install livewire
  3. The team editionphp artisan jetstream:install livewire --teams
  4. npm install
  5. npm run dev
  6. Local configuration data is synchronized to the databasephp artisan migrateIf if there is an error here, modify itconfig/database.phpcoding
'charset' => 'utf8',
'collation' => 'utf8_general_ci', 
Copy the code
  1. Registered address at first loginhttp://127.0.0.1:8000/register
According to the component

The Blade component PHP artisan vendor:publish –tag=jetstream-views is displayed

Location of Blade component resources/views/vendor/

Close registration etc

config/fortify.php

Return ['features' => [// features ::registration(),// Disable registration features ::resetPasswords(), / / the Features: : emailVerification (), / / close mailbox to verify the Features: : updateProfileInformation (), the Features: : updatePasswords (), [/ / / / the Features: : twoFactorAuthentication (close to add a second validation / / 'confirmPassword' = > true, / /]),]];Copy the code
Close and delete an Account

config/jetstream.php

'features' => [ // Features::termsAndPrivacyPolicy(), // Features::profilePhotos(), // Features::api(), The Features: : teams ([' invitations' = > false]), do not use the send mail invitation patterns / / / false/Features: : accountDeletion (), / / close the account deletion function]];Copy the code
Login verification code

Adding a login verification code to the log-in page in Laravel8 was a bit complicated, but it worked.

Captcha plug-in github.com/mewebstudio…

  1. The installationcomposer require mews/captcha
  2. configurationconfig/app.php
'will' = > [/ /... Mews \ Captcha \ CaptchaServiceProvider: : class, / / verification code] 'aliases' = >' Captcha '= > / / /... Mews\Captcha\Facades\Captcha::class,// Verification code]Copy the code
  1. The verification code configuration is displayedphp artisan vendor:publishlocationconfig/captcha.php
  2. newapp/Actions/Fortify/CaptchaValidation.php
<?php

namespace App\Actions\Fortify;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CaptchaValidation
{
    public function __invoke(Request $request, $next)
    {
        Validator::make($request->all(), [
            'captcha' => 'required|captcha'
        ])->validate();

        return $next($request);
    }
}
Copy the code
  1. configurationapp/Providers/JetstreamServiceProvider.php
Use Illuminate\Http\Request; use App\Actions\Fortify\CaptchaValidation; use Laravel\Fortify\Actions\AttemptToAuthenticate; use Laravel\Fortify\Actions\EnsureLoginIsNotThrottled; use Laravel\Fortify\Actions\PrepareAuthenticatedSession; public function boot() { $this->configurePermissions(); Jetstream::createTeamsUsing(CreateTeam::class); Jetstream::updateTeamNamesUsing(UpdateTeamName::class); Jetstream::addTeamMembersUsing(AddTeamMember::class); Jetstream::inviteTeamMembersUsing(InviteTeamMember::class); Jetstream::removeTeamMembersUsing(RemoveTeamMember::class); Jetstream::deleteTeamsUsing(DeleteTeam::class); Jetstream::deleteUsersUsing(DeleteUser::class); / / captcha Fortify: : authenticateThrough (function (Request $Request) {return array_filter ([config (' Fortify. Limiters. Login)  ? null : EnsureLoginIsNotThrottled::class, CaptchaValidation::class, AttemptToAuthenticate::class, PrepareAuthenticatedSession::class, ]); }); }Copy the code
  1. The login pageresources/views/vendor/auth/login.blade.php
<div class="mt-4">
    <x-jet-label for="captcha" value="{{ __('Captcha') }}" />
    <span class="block mt-1 float-right">@php  echo captcha_img('flat'); @endphp</span>
    <x-jet-input id="captcha" class="block mt-1 w-30" type="text" name="captcha" required autocomplete="current-captcha" />
</div>
Copy the code

Also, PHP on Mac does not come with Freetype, so the solution is to install PHP again. Then restart the computer, it must work. www.jianshu.com/p/09f3ea8ac…

WeChat

Github.com/overtrue/la…

  • Version forPHP > = 7.4
  • If the installation fails, update itcomposerversioncomposer self-update
  • The installationComposer require "overture/laravel - wechat: ^ 6.0"
  • It seems that ali Cloud image must be usedcomposer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
  • Creating a Configuration Filephp artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
Middleware retrieves user information
  1. routingroutes/web.php
Route::any('/wechat/oauth', [WeChat::class, 'oauth'])->middleware('wechat.oauth');
Copy the code
  1. The controllerapp/Http/Controllers/WeChat.php
public function oauth(){
    return dd(session('wechat.oauth_user.default.raw'));
}
Copy the code
Wechat sharing function
  1. The controllerapp/Http/Controllers/WeChat.php
public function share(){ $app = app('wechat.official_account'); $APIs = ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage']; $jssdk = $app->jssdk->buildConfig($APIs, $debug = false, $beta = false, $json = true); = $config [' title '= >' title1, / / share the title 'desc' = > 'desc1', / / share describe 'link' = > url () - > the current (), / / share links, ImgUrl '=> '/images/oy. Jpeg ', // Share icon]; return view('wechat.share',[ 'jssdk' => $jssdk, 'config' => $config, ]); }Copy the code
  1. According toresources/views/wechat/share.blade.php
< script SRC = "http://res.wx.qq.com/open/js/jweixin-1.6.0.js" > < / script > < script > wx. Config ({!!!!! $jssdk!! }); Wx. Ready (function () {wx. UpdateAppMessageShareData ({title: '{{$config [' title']}} ', / / share title desc: $config['desc']}} link: '{{$config['link']}}', // Share link: '{{$config['link']}}', // share link: {{$config['link']}}', // share link: '{{url ('/')}} {{$config [' imgUrl]}}', / / share icon success: the function () {/ / set up successful alert (' updateAppMessageShareData111 '); }}) wx. UpdateTimelineShareData ({title: '{{$config [' title']}} ', / / share title desc: '{{$config [' desc']}} ', / / share describe the link: ImgUrl: {{$config['link']}} {$config['link']}} '{{url ('/')}} {{$config [' imgUrl]}}', / / share icon success: the function () {/ / set up successful alert (' updateTimelineShareData222 '); }}) wx. OnMenuShareTimeline ({/ / going to scrap the title: '{{$config [' title']}} ', / / share title desc: '{{$config [' desc']}} ', / / share describe the link: ImgUrl: {{$config['link']}} {$config['link']}} '{{url ('/')}} {{$config [' imgUrl]}}', / / share icon success: the function () {/ / set up successful alert (' onMenuShareTimeline333 '); }}) wx.onMenuShareAppMessage({{$config['title']}}', // share title desc: $config['desc']}} link: '{{$config['link']}}', // Share link: '{{$config['link']}}', // share link: {{$config['link']}}', // share link: '{{url ('/')}} {{$config [' imgUrl]}}', / / share icon success: the function () {/ / set up successful alert (' onMenuShareAppMessage444 '); }})}); </script>Copy the code

debugging

Github.com/barryvdh/la…

  1. The installationcomposer require barryvdh/laravel-debugbar --dev
  2. Shut down.env APP_DEBUG=falseorconfig/app.php 'debug' => false
  3. use\Debugbar::info('OY');

The deployment of

There is nothing to be said for deploying to the root directory, it is more about how to deploy to subdirectories.

Methods a
  1. http://127.0.0.1/travel/rrm/
  2. The root directoryserver.phpChanged its name intoindex.php
  3. public/.htaccess
    <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /travel/rrm/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} ! -f RewriteCond %{REQUEST_FILENAME} ! -d RewriteRule . /travel/rrm/index.php [L] </IfModule>Copy the code
  4. public/mix-manifest.json
    {"/js/app. Js ":" http://127.0.0.1/travel/rrm/public/js/app.js ", "/ CSS/app. CSS" : "Http://127.0.0.1/travel/rrm/public/css/app.css"}Copy the code
  5. php artisan livewire:publish
  6. config/livewire.php
    'asset_url' = > 'http://127.0.0.1/travel/rrm',Copy the code
Method 2
  1. http://127.0.0.1/travel/rrm/
  2. Browser inputhttp://127.0.0.1/travel/rrm/public/
  3. Don’t need to configurepublic/.htaccessAnd then 456 as above

Continuously updated