当前位置:网站首页>Laravel study notes

Laravel study notes

2022-06-24 23:13:00 Wang Daochang's way of programming

One 、router

<?php

use Illuminate\Support\Facades\Route;

/* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */
//
//Route::get('/', function () {
    
//
// return view('welcome');
//});

Route::resource('task', 'TaskController');
/* Route::post('/', function () {}); Route::put('/', function () {}); Route::delete('/', function () {}); Route::any('/', function () {}); Route::match(['get', 'post'], '/', function () {}); Route::get('/', '[email protected]'); Route::get('user/{id}', function ($id) { return " user ID: " . $id; }); Route::get('page/{id}', function ($id) { return ' page ID: ' . $id; })->where('id', '[0-9]+'); Route::get('page/{name}', function ($name) { return ' Page name : ' . $name; })->where('name', '[A-Za-z]+'); Route::get('page/{id}/{slug}', function ($id, $slug) { return $id . ':' . $slug; })->where(['id' => '[0-9]+', 'slug' => '[A-Za-z]+']); ### section B Route::group([], function () { Route::get('hello', function () { return 'Hello'; }); Route::get('world', function () { return 'World'; }); }); // route - middleware  Route::middleware('auth')->group(function () { Route::get('dashboard', function () { return view('dashboard'); }); Route::get('account', function () { return view('account'); }); }); //  Routing grouping  Route::group(['middleware' => 'auth'], function () { Route::get('dashboard', function () { return view('dashboard'); }); Route::get('account', function () { return view('account'); }); }); //  route - Prefix  Route::prefix('api')->group(function () { Route::get('/', function () { //  Handle  /api  route  })->name('api.index'); Route::get('users', function () { //  Handle  /api/users  route  })->name('api.users'); }); //  route - domain name  Route::domain('admin.blog.test')->group(function () { Route::get('/', function () { //  Handle  http://admin.blog.test  route  }); }); Route::domain('{account}.blog.test')->group(function () { Route::get('/', function ($account) { // }); Route::get('user/{id}', function ($account, $id) { // }); }); Route::get('/', '[email protected]'); //  route - Namespace  Route::namespace('Admin')->group(function() { // App\Http\Controllers\Admin\AdminController Route::get('/admin', '[email protected]'); }); //  Route naming + Path prefix  Route::name('user.')->prefix('user')->group(function () { Route::get('{id?}', function ($id = 1) { //  Handle  /user/{id}  route , The route is named  user.show return route('user.show'); })->name('show'); Route::get('posts', function () { //  Handle  /user/posts  route , The route is named  user.posts })->name('posts'); }); // route - resources  Route::resource('post', 'PostController'); // route - Model  Route::get('task/{task}', function(\App\Task $task){ dd($task); }); // route - The bottom line  Route::fallback(function(){ return ' I'm the one who knows everything '; }); // route - Frequency limit  Route::middleware('throttle:60,1')->group(function(){ Route::get('/usr', function(){ }); }); Route::middleware('throttle:rate_limit, 1')->group(function(){ Route::get('/user', function () { //  stay  User  Set custom in the model  rate_limit  Property value  }); Route::get('/post', function () { //  stay  Post  Set custom in the model  rate_limit  Property value  }); }); // The routing cache  php artisan route:cache # If closures are used in routing, an error will be reported  php artisan route:clear */


//section C  View 
/*
// Laravel  View overview 
return view(' With . Separate view template paths ');
// View return and parameter transfer 
//  Use  view  Auxiliary function 
Route::get('/', function () {
    
    //  This function will be in  resources/views  Directory lookup  home.blade.php  or  home.php  view file ,
    //  Load the contents of the file and parse  PHP  A variable or statement , Then pass it to the response , Finally presented to the user 
    return view('home');
});
return view('home')->with('tasks', Task::all());
return view('home', ['tasks' => Task::all()]);
// View - Global shared variables 
view()->share('siteName', 'Laravel college ');
view()->share('siteUrl', 'https://xueyuanjun.com');
// View - Locally shared variables 
view()->composer('partials.sidebar', function ($view) {
    
    $view->with('posts', Post::recent());
});
// View - Custom data presets 
view()->composer( 'partials.sidebar', \App\Http\ViewComposers\RecentPostsComposer::class );
//  Specify multiple view components through wildcards 
view()->composer('partials.*', function ($view) {
    
    $view->with('posts', Post::recent());
});

Two 、blade

//section D Blade  template engine 
/* // Inject services into the view  @inject('analytics', 'App\Services\Analytics') <div class="finances-display"> {
    { $analytics->getBalance() }} / {
    { $analytics->getBudget() }} </div> */

//section E Resquest  object 
/* //  adopt  $request  Instance to get request data  dd($request->all()); // Get some request data  $request->only(); $request->except(); // Get a single field  $request->input(); $request->segments(); // Determine whether the field is included  $request->has(); */
// section F  controller 
/* // verification  $this->validate($request, [ 'title' => 'bail|required|string|between:2,32', 'url' => 'sometimes|url|max:200', 'picture' => 'nullable|string' ]);  Validation rule :https://xueyuanjun.com/post/9547.html#toc_17 $this->validate($request, [ 'title' => 'bail|required|string|between:2,32', 'url' => 'sometimes|url|max:200', 'picture' => 'nullable|string' ], [ 'title.required' => ' Title field cannot be empty ', 'title.string' => ' The title field only supports strings ', 'title.between' => ' Title length must be between 2-32 Between ', 'url.url' => 'URL Incorrect format , Please enter a valid URL', 'url.max' => 'URL The length cannot exceed 200', ]); */

//section G DB
/*
// Use  DB  Facade execution  SQL  sentence 
DB::statement('drop table `users`');
$users = DB::select('select * from `users`');

PHP  Of  PDO  Realization 
$name = ' Academician ';
$users = DB::select('select * from `users` where `name` = ?', [$name]);

$name = str_random(10);
$email = str_random(10) . '@163.com';
$password = bcrypt('secret');
$flag = DB::insert('insert into `users` (`name`, `email`, `password`) values (?, ?, ?)', [$name, $email, $password]);

$name = str_random(8);
$id = 8;
$affectedRows = DB::update('update `users` set `name` = ? where id = ?', [$name, $id]);

$id = 8;
$affectedRows = DB::delete('delete from `users` where id = ?', [$id]);

// Use the query builder to add, delete, modify, and query 
$name = ' Academician ';
$users = DB::table('users')->where('name', $name)->get();
$user = DB::table('users')->where('name', $name)->first();
$user = DB::table('users')->select('id', 'name', 'email')->where('name', $name)->first();

$flag = DB::table('users')->insert([
    'name' => str_random(10),
    'email' => str_random(8) . '@163.com',
    'password' => bcrypt('secret')
]);

$userId = DB::table('users')->insertGetId([
    'name' => str_random(10),
    'email' => str_random(8) . '@qq.com',
    'password' => bcrypt('secret')
]);

DB::table('users')->insert([
    ['name' => str_random(10), 'email' => str_random(8) . '@qq.com', 'password' => bcrypt('123')],
    ['name' => str_random(10), 'email' => str_random(8) . '@qq.com', 'password' => bcrypt('456')],
    ['name' => str_random(10), 'email' => str_random(8) . '@qq.com', 'password' => bcrypt('789')],
]);( If inserted out  QueryException  abnormal , Will be interrupted as a whole , Not a single one will be inserted .)

$id = 11;
$affectedRows = DB::table('users')->where('id', '>', $id)->update(['name' => str_random(8)]);
DB::table('posts')->where('id', 100)->increment('views'); // views+1
DB::table('posts')->where('id', 100)->increment('views', 5); // views+5
DB::table('posts')->where('id', 100)->decrement('votes');  // votes-1

$id = 11;
$affectedRows = DB::table('users')->where('id', '>=', $id)->delete();
$affectedRows = DB::table('users')->delete();
$affectedRows = DB::table('users')->truncate();

// Inquiry skills 
$name = ' Academician ';
$email = DB::table('users')->where('name', $name)->value('email'); Get the value of the specified field 
$exists = DB::table('users')->where('name', $name)->exists(); Determine whether a field value has a corresponding record in the database 
$users = DB::table('users')->where('id', '<', 10)->pluck('name', 'id'); With primary key  ID  Value is key , Construct an associative array with a field value as the value 
 A one-time return may exceed  PHP  Memory limit , At this time, with the help of  chunk  Method divides it into multiple chunks and returns in turn :
$names = [];
DB::table('users')->orderBy('id')->chunk(5, function ($users) use (&$names) {
    
    foreach ($users as $user) {
    
        $names[] = $user->name;
    }
});
$num = DB::table('users')->count();       #  Count  9
$sum = DB::table('users')->sum('id');     #  Sum up  45
$avg = DB::table('users')->avg('id');     #  Average  5
$min = DB::table('users')->min('id');     #  minimum value  1
$max = DB::table('users')->max('id');     #  Maximum  9

// senior  Where  Inquire about  =、>、<、<>
DB::table('posts')->where('views', 0)->get();      #  The equal sign can be omitted here 
DB::table('posts')->where('views', '>', 0)->get();
DB::table('posts')->where('views', '<>', 0)->get();
# where-like
DB::table('posts')->where('title', 'like', 'Laravel college %')->get();
# where-and
DB::table('posts')->where('id', '<', 10)->where('views', '>', 0)->get();
# where-or
DB::table('posts')->where('id', '<', 10)->orWhere('views', '>', 0)->get();
# where-between
DB::table('posts')->whereBetween('views', [10, 100])->get();
DB::table('posts')->whereNotBetween('views', [10, 100])->get();
# where-in
DB::table('posts')->whereIn('user_id', [1, 3, 5, 7, 9])->get();
# where-null
DB::table('users')->whereNull('email_verified_at')->get();
DB::table('users')->whereNotNull('email_verified_at')->get();
# where- date 
DB::table('posts')->whereYear('created_at', '2018')->get();   #  year 
DB::table('posts')->whereMonth('created_at', '11')->get();    #  month 
DB::table('posts')->whereDay('created_at', '28')->get();      #  The day of the month 
DB::table('posts')->whereDate('created_at', '2018-11-28')->get();  #  Specific date 
DB::table('posts')->whereTime('created_at', '14:00')->get();  #  Time 
# where- Field comparison 
DB::table('posts')->whereColumn('updated_at', '>', 'created_at')->get();
# where-json
DB::table('users')
    ->where('options->language', 'en')
    ->get();
select * from `users` where json_unquote(json_extract(`options`, '$."language"')) = en
DB::table('users')
    ->whereJsonContains('options->languages', 'en_US')
    ->get();
select * from `users` where json_contains(`options`, "en_US", '$."languages"')
DB::table('users')
    ->whereJsonContains('options->languages', ['en_US', 'zh_CN'])
    ->get();
# where- Parameter grouping 
DB::table('posts')->where('id', '<=', 10)->orWhere(function ($query) {
    
    $query->where('views', '>', 0)
        ->whereDate('created_at', '<', '2018-11-28')
        ->whereTime('created_at', '<', '14:00');
})->get();
select * from posts where id <= 10 or (views > 0 and created_at < '2018-11-28 14:00');
# where-Exists
DB::table('users')
    ->whereExists(function ($query) {
    
        $query->select(DB::raw(1))
            ->from('posts')
            ->whereRaw('posts.user_id = users.id');
    })
->get();
select * from `users` where exists (select 1 from `posts` where posts.user_id = users.id);
# where- Subquery 
$users = DB::table('users')->whereNotNull('email_verified_at')->select('id');
$posts = DB::table('posts')->whereInSub('user_id', $users)->get();
select * from posts where user_id in (select id from users where email_verified_at is not null);

// Link query 
$posts = DB::table('posts')
    ->leftJoin('users', 'users.id', '=', 'posts.user_id')
    ->select('posts.*', 'users.name', 'users.email')
    ->get();# league of the left-wing writers 
select posts.*, users.name, users.email from posts left join users on users.id = posts.user_id;
$posts = DB::table('posts')
    ->rightJoin('users', 'users.id', '=', 'posts.user_id')
    ->select('posts.*', 'users.name', 'users.email')
    ->get();# Right couplet 
select posts.*, users.name, users.email from posts right join users on users.id = posts.user_id;
$posts = DB::table('posts')
    ->join('users', function ($join) {
    
        $join->on('users.id', '=', 'posts.user_id')
            ->whereNotNull('users.email_verified_at');
    })
    ->select('posts.*', 'users.name', 'users.email')
    ->where('posts.views', '>', 0)
    ->get();# Other connections 
select posts.*, users.name, users.email from posts inner join users on users.id = posts.user_id and users.email_verified_at is not null where posts.views > 0;
$posts_a = DB::table('posts')->where('views', 0);
$posts_b = DB::table('posts')->where('id', '<=', 10)->union($posts_a)->get();( The joint query )
(select * from `posts` where `id` <= 10) union (select * from `posts` where `views` = 0)
// grouping 
$posts = DB::table('posts')
    ->groupBy('user_id')
    ->selectRaw('user_id, sum(views) as total_views')
    ->get();
select user_id, sum(views) as total_views from `posts` group by `user_id`;
// Pagination 
$posts = DB::table('posts')->orderBy('created_at', 'desc')
    ->where('views', '>', 0)
    ->skip(10)->take(5)
    ->get();
$posts = DB::table('posts')->orderBy('created_at', 'desc')
    ->where('views', '>', 0)
    ->offset(10)->limit(5)
    ->get();
select * from `posts` where `views` > 0 order by `created_at` desc limit 5 offset 10;
*/

// Eloquent  Model 
/* // Table name  protected $table = 'articles'; // Primary key  protected $primaryKey = 'post_id'; public $incrementing = false; protected $keyType = 'string'; // Time stamp  public $timestamps = false; public const CREATED_AT = 'create_time'; public const UPDATED_AT = 'update_time'; protected $dateFormat = 'U'; // Database connection  protected $connection = 'connection_name'; // Inquire about  $posts = Post::all(); Post::chunk(10, function ($posts) { foreach ($posts as $post) { if ($post->views == 0) { continue; } else { dump($post->title . ':' . $post->views); } } }); foreach (Post::cursor() as $post) { dump($post->title . ':' . $post->content); } // Get the specified query result  $posts = Post::where('views', '>', 0)->select('id', 'title', 'content')->get(); $posts = Post::where('views', '>', 0)->orderBy('id', 'desc')->offset(10)->limit(5)->get(); // Get a single record  $user = User::where('name', ' Academician ')->first(); $user = User::find(1);# The query condition is primary key  ID $user = User::findOrFail(111);# When the return result of a single record is null, it returns  404  Respond to  // Get aggregation results  $num = User::whereNotNull('email_verified_at')->count(); #  Count  $sum = User::whereNotNull('email_verified_at')->sum('id'); #  Sum up  $avg = User::whereNotNull('email_verified_at')->avg('id'); #  Average  $min = User::whereNotNull('email_verified_at')->min('id'); #  minimum value  $max = User::whereNotNull('email_verified_at')->max('id'); #  Maximum  // insert data  $post = new App\Post; $post->title = ' Test article title '; $post->content = ' Test article content '; $post->user_id = 1; $post->save(); // Update data  $post = Post::find(31); $post->title = ' Test article title update '; $post->save(); $user = user::updateOrCreate( ['name' => ' Academician '], ['email' => '[email protected]'] );# If the corresponding record does not exist , Then insert the database , And save ( Don't suggest ) Post::where('views', '>', 0)->update(['views' => 100]);# Batch update  // Delete data  $post = Post::find(31); $post->delete();# For the data table id=31 Of the records deleted  Post::destroy([1,2,3]);# Delete multiple items at once  $user = User::where('name', ' Academician ')->fisrt(); $user->delete();# Delete the first  protected $fillable = [];# Use attributes assigned in batches ( White list ) protected $guarded = ['*'];# Fields that do not use batch assignment ( The blacklist ) // Update the model  $post = Post::findOrFail(11); $post->fill($request->all()); # Batch assignment  $post->save(); // Soft delete  //php artisan make:migration alter_posts_add_deleted_at --table=posts public function up() { Schema::table('posts', function (Blueprint $table) { $table->softDeletes(); }); } class Post extends Model { use SoftDeletes; protected $guarded = ['user_id']; } $post = Post::findOrFail(32); $post->delete(); if ($post->trashed()) { dump(' The record has been deleted '); } $post = Post::withTrashed()->find(32); $post = Post::onlyTrashed()->where('views', 0)->get(); $post->restore(); //  Restore a single record  Post::onlyTrashed()->where('views', 0)->restore(); //  Recover multiple records  $post->forceDelete();# Physically delete data table records  // Accessors and modifiers  public function getDisplayNameAttribute() { return $this->nickname ? $this->nickname : $this->name; } # visit :$user->display_name public function setCardNoAttribute($value) { $value = str_replace(' ', '', $value); //  Remove all spaces  $this->attributes['card_no'] = encrypt($value); } # Set up :$user->card_no = '6222020903001483077'; #  Array rotation json // Global scope and local scope  // Model event listening  retrieved: Trigger after getting the model instance  creating: Triggered before inserting into the database  created: Triggered after inserting into the database  updating: Triggered before updating to the database  updated: Triggered after updating to the database  saving: Triggered before saving to the database ( Insert / Before updating , Both insert and update will trigger ) saved: Triggered after saving to the database ( Insert / After the update , Both insert and update will trigger ) deleting: Triggered before deleting a record from the database  deleted: Triggered after deleting a record from the database  restoring: Triggered before restoring soft delete records  restored: Triggered after recovering soft delete records  //  Static methods listen for model events  app/Providers/EventServiceProvider.php public function boot(){ parent::boot(); //  Listen to the model to get events  User::retrieved(function ($user) { Log::info(' Get users from the model [' . $user->id . ']:' . $user->name); }); } // Subscriber listens for model events  php artisan make:event UserDeleting php artisan make:event UserDeleted // app/Events/UserDeleted.php // app/Events/UserDeleting.php public $user; public function __construct(User $user) { $this->user = $user; } //App/User.php protected $dispatchesEvents = [ 'deleting' => UserDeleting::class, 'deleted' => UserDeleted::class ]; // The observer listens to model events  // Connections  */

One 、

# -m  Generate a create——migration, however migration It will automatically add s
php artisan make:model blog -m

Two 、 Batch fill

2.1 Create data table class

# --create : Table name , Create entity tables in the database 
php artisan make:migration create_posts_table --create=posts

2.2 Define table fields , Synchronization mysql

public function up()
{
    
    Schema::create('posts', function (Blueprint $table) {
    
        $table->increments('id');
        $table->string('title')->comment(' title ');
        $table->text('content')->comment(' Content ');
        $table->integer('user_id')->unsigned()->default(0);
        $table->integer('views')->unsigned()->default(0)->comment(' Browse the number ');
        $table->index('user_id');
        $table->timestamps();
    });
}

Create data table

php artisan migrate 

Create the corresponding model class

php artisan make:model Post

Create a model factory for the model class

# --model : Defined postfactory in define With model name 
php artisan make:factory PostFactory --model=Post

Write model class methods :database/factories/PostFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(\App\Post::class, function (Faker $faker) {
    
    return [
        'title' => $faker->title,
        'content' => $faker->text,
        'user_id' => mt_rand(1, 15),
        'views' => $faker->randomDigit
    ];
});

And then to posts Table create fill class :

php artisan make:seeder PostsTableSeeder

stay database/seeds The newly generated fill class in the directory PostsTableSeeder in , Call the model factory to fill the data table :

<?php

use Illuminate\Database\Seeder;

class PostsTableSeeder extends Seeder{
    
    /** * Run the database seeds. * * @return void */
    public function run()
    {
    
        factory(\App\Post::class, 30)->create();
    }
}

Run the following Artisan Command fill posts The data table shows :

php artisan db:seed --class=PostsTableSeeder

Create our first Article Model and its corresponding migration file , We run the following in the project root directory Artisan One step command

php artisan make:model Article -m

Edit the migration file generated by default :

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    
    /** * Run the migrations. * * @return void */
    public function up()
    {
    
        Schema::create('articles', function (Blueprint $table) {
    
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /** * Reverse the migrations. * * @return void */
    public function down()
    {
    
        Schema::dropIfExists('articles');
    }
}

Run the following command to create the corresponding data table :

php artisan migrate
原网站

版权声明
本文为[Wang Daochang's way of programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241719270985.html