当前位置:网站首页>laravel学习笔记
laravel学习笔记
2022-06-24 19:41:00 【王道长的编程之路】
一、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 "用户ID: " . $id; }); Route::get('page/{id}', function ($id) { return '页面ID: ' . $id; })->where('id', '[0-9]+'); Route::get('page/{name}', function ($name) { return '页面名称: ' . $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('auth')->group(function () { Route::get('dashboard', function () { return view('dashboard'); }); Route::get('account', function () { return view('account'); }); }); // 路由分组 Route::group(['middleware' => 'auth'], function () { Route::get('dashboard', function () { return view('dashboard'); }); Route::get('account', function () { return view('account'); }); }); // 路由-前缀 Route::prefix('api')->group(function () { Route::get('/', function () { // 处理 /api 路由 })->name('api.index'); Route::get('users', function () { // 处理 /api/users 路由 })->name('api.users'); }); // 路由-域名 Route::domain('admin.blog.test')->group(function () { Route::get('/', function () { // 处理 http://admin.blog.test 路由 }); }); Route::domain('{account}.blog.test')->group(function () { Route::get('/', function ($account) { // }); Route::get('user/{id}', function ($account, $id) { // }); }); Route::get('/', '[email protected]'); // 路由-命名空间 Route::namespace('Admin')->group(function() { // App\Http\Controllers\Admin\AdminController Route::get('/admin', '[email protected]'); }); // 路由命名+路径前缀 Route::name('user.')->prefix('user')->group(function () { Route::get('{id?}', function ($id = 1) { // 处理 /user/{id} 路由,路由命名为 user.show return route('user.show'); })->name('show'); Route::get('posts', function () { // 处理 /user/posts 路由,路由命名为 user.posts })->name('posts'); }); //路由-资源 Route::resource('post', 'PostController'); //路由-模型 Route::get('task/{task}', function(\App\Task $task){ dd($task); }); //路由-兜底 Route::fallback(function(){ return '我是兜底路由'; }); //路由-频率限制 Route::middleware('throttle:60,1')->group(function(){ Route::get('/usr', function(){ }); }); Route::middleware('throttle:rate_limit, 1')->group(function(){ Route::get('/user', function () { // 在 User 模型中设置自定义的 rate_limit 属性值 }); Route::get('/post', function () { // 在 Post 模型中设置自定义的 rate_limit 属性值 }); }); //路由缓存 php artisan route:cache #如果路由中使用闭包会报错 php artisan route:clear */
//section C 视图
/*
// Laravel 视图概述
return view('以.分隔的视图模板路径');
//视图返回与参数传递
// 使用 view 辅助函数
Route::get('/', function () {
// 该函数会在 resources/views 目录下查找 home.blade.php 或 home.php 视图文件,
// 加载文件内容并解析 PHP 变量或语句,然后传递给响应,最终呈现给用户
return view('home');
});
return view('home')->with('tasks', Task::all());
return view('home', ['tasks' => Task::all()]);
//视图-全局共享变量
view()->share('siteName', 'Laravel学院');
view()->share('siteUrl', 'https://xueyuanjun.com');
//视图-局部共享变量
view()->composer('partials.sidebar', function ($view) {
$view->with('posts', Post::recent());
});
//视图-自定义数据预设
view()->composer( 'partials.sidebar', \App\Http\ViewComposers\RecentPostsComposer::class );
// 通过通配符指定多个视图组件
view()->composer('partials.*', function ($view) {
$view->with('posts', Post::recent());
});
二、blade
//section D Blade 模板引擎
/* //视图中注入服务 @inject('analytics', 'App\Services\Analytics') <div class="finances-display"> {
{ $analytics->getBalance() }} / {
{ $analytics->getBudget() }} </div> */
//section E Resquest 对象
/* // 通过 $request 实例获取请求数据 dd($request->all()); //获取部分请求数据 $request->only(); $request->except(); //获取单个字段 $request->input(); $request->segments(); //判断是否包含字段 $request->has(); */
// section F 控制器
/* //验证 $this->validate($request, [ 'title' => 'bail|required|string|between:2,32', 'url' => 'sometimes|url|max:200', 'picture' => 'nullable|string' ]); 验证规则: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.string' => '标题字段仅支持字符串', 'title.between' => '标题长度必须介于2-32之间', 'url.url' => 'URL格式不正确,请输入有效的URL', 'url.max' => 'URL长度不能超过200', ]); */
//section G DB
/*
//使用 DB 门面执行原生 SQL 语句
DB::statement('drop table `users`');
$users = DB::select('select * from `users`');
PHP 的 PDO 实现
$name = '学院君';
$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]);
//使用查询构建器进行增删改查
$name = '学院君';
$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')],
]);(如果插入出 QueryException 异常,会整体中断,一条都不会插进去。)
$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();
//查询技巧
$name = '学院君';
$email = DB::table('users')->where('name', $name)->value('email');获取指定字段的值
$exists = DB::table('users')->where('name', $name)->exists();判断某个字段值在数据库中是否存在对应记录
$users = DB::table('users')->where('id', '<', 10)->pluck('name', 'id');以主键 ID 值为键,以某个字段值为值构建关联数组
一次性返回可能会超出 PHP 内存限制,这时借助 chunk 方法将其分割成多个组块依次返回:
$names = [];
DB::table('users')->orderBy('id')->chunk(5, function ($users) use (&$names) {
foreach ($users as $user) {
$names[] = $user->name;
}
});
$num = DB::table('users')->count(); # 计数 9
$sum = DB::table('users')->sum('id'); # 求和 45
$avg = DB::table('users')->avg('id'); # 平均值 5
$min = DB::table('users')->min('id'); # 最小值 1
$max = DB::table('users')->max('id'); # 最大值 9
//高级 Where 查询 =、>、<、<>
DB::table('posts')->where('views', 0)->get(); # 此处等号可以省略
DB::table('posts')->where('views', '>', 0)->get();
DB::table('posts')->where('views', '<>', 0)->get();
# where-like
DB::table('posts')->where('title', 'like', 'Laravel学院%')->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-日期
DB::table('posts')->whereYear('created_at', '2018')->get(); # 年
DB::table('posts')->whereMonth('created_at', '11')->get(); # 月
DB::table('posts')->whereDay('created_at', '28')->get(); # 一个月的第几天
DB::table('posts')->whereDate('created_at', '2018-11-28')->get(); # 具体日期
DB::table('posts')->whereTime('created_at', '14:00')->get(); # 时间
# where-字段比较
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-参数分组
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-子查询
$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);
//连接查询
$posts = DB::table('posts')
->leftJoin('users', 'users.id', '=', 'posts.user_id')
->select('posts.*', 'users.name', 'users.email')
->get();#左联
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();#右联
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();#其它连接
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();(联合查询)
(select * from `posts` where `id` <= 10) union (select * from `posts` where `views` = 0)
//分组
$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`;
//分页
$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 模型
/* //表名 protected $table = 'articles'; //主键 protected $primaryKey = 'post_id'; public $incrementing = false; protected $keyType = 'string'; //时间戳 public $timestamps = false; public const CREATED_AT = 'create_time'; public const UPDATED_AT = 'update_time'; protected $dateFormat = 'U'; //数据库连接 protected $connection = 'connection_name'; //查询 $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); } //获取指定查询结果 $posts = Post::where('views', '>', 0)->select('id', 'title', 'content')->get(); $posts = Post::where('views', '>', 0)->orderBy('id', 'desc')->offset(10)->limit(5)->get(); //获取单条记录 $user = User::where('name', '学院君')->first(); $user = User::find(1);#查询的条件是主键 ID $user = User::findOrFail(111);#单条记录返回结果为空时返回 404 响应 //获取聚合结果 $num = User::whereNotNull('email_verified_at')->count(); # 计数 $sum = User::whereNotNull('email_verified_at')->sum('id'); # 求和 $avg = User::whereNotNull('email_verified_at')->avg('id'); # 平均值 $min = User::whereNotNull('email_verified_at')->min('id'); # 最小值 $max = User::whereNotNull('email_verified_at')->max('id'); # 最大值 //插入数据 $post = new App\Post; $post->title = '测试文章标题'; $post->content = '测试文章内容'; $post->user_id = 1; $post->save(); //更新数据 $post = Post::find(31); $post->title = '测试文章标题更新'; $post->save(); $user = user::updateOrCreate( ['name' => '学院君'], ['email' => '[email protected]'] );#如果发现对应记录不存在,则插入数据库,并保存(不建议) Post::where('views', '>', 0)->update(['views' => 100]);#批量更新 //删除数据 $post = Post::find(31); $post->delete();#对数据表id=31的记录删除 Post::destroy([1,2,3]);#一次删除多条 $user = User::where('name', '学院君')->fisrt(); $user->delete();#删除第一条 protected $fillable = [];#使用批量赋值的属性(白名单) protected $guarded = ['*'];#不使用批量赋值的字段(黑名单) //更新模型 $post = Post::findOrFail(11); $post->fill($request->all()); #批量赋值 $post->save(); //软删除 //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('该记录已删除'); } $post = Post::withTrashed()->find(32); $post = Post::onlyTrashed()->where('views', 0)->get(); $post->restore(); // 恢复单条记录 Post::onlyTrashed()->where('views', 0)->restore(); // 恢复多条记录 $post->forceDelete();#物理删除数据表记录 //访问器和修改器 public function getDisplayNameAttribute() { return $this->nickname ? $this->nickname : $this->name; } #访问:$user->display_name public function setCardNoAttribute($value) { $value = str_replace(' ', '', $value); // 将所有空格去掉 $this->attributes['card_no'] = encrypt($value); } #设置:$user->card_no = '6222020903001483077'; # 数组转json //全局作用域和局部作用域进行查询 //模型事件监听 retrieved:获取到模型实例后触发 creating:插入到数据库前触发 created:插入到数据库后触发 updating:更新到数据库前触发 updated:更新到数据库后触发 saving:保存到数据库前触发(插入/更新之前,无论插入还是更新都会触发) saved:保存到数据库后触发(插入/更新之后,无论插入还是更新都会触发) deleting:从数据库删除记录前触发 deleted:从数据库删除记录后触发 restoring:恢复软删除记录前触发 restored:恢复软删除记录后触发 // 静态方法监听模型事件 app/Providers/EventServiceProvider.php public function boot(){ parent::boot(); // 监听模型获取事件 User::retrieved(function ($user) { Log::info('从模型中获取用户[' . $user->id . ']:' . $user->name); }); } //订阅者监听模型事件 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 ]; //观察者监听模型事件 //关联关系 */
一、
# -m 同时生成一个create——migration,不过migration会自动添加s
php artisan make:model blog -m
二、批量填充
2.1 创建数据表类
# --create :表名,在数据库中创建实体表
php artisan make:migration create_posts_table --create=posts
2.2 定义表字段,并同步mysql
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->comment('标题');
$table->text('content')->comment('内容');
$table->integer('user_id')->unsigned()->default(0);
$table->integer('views')->unsigned()->default(0)->comment('浏览数');
$table->index('user_id');
$table->timestamps();
});
}
创建数据表
php artisan migrate
创建对应的model类
php artisan make:model Post
为模型类创建一个模型工厂
# --model :定义了postfactory里define用的model名称
php artisan make:factory PostFactory --model=Post
编写模型类方法: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
];
});
然后为 posts 表创建填充类:
php artisan make:seeder PostsTableSeeder
在 database/seeds 目录下新生成的填充类 PostsTableSeeder 中,调用模型工厂填充数据表:
<?php
use Illuminate\Database\Seeder;
class PostsTableSeeder extends Seeder{
/** * Run the database seeds. * * @return void */
public function run()
{
factory(\App\Post::class, 30)->create();
}
}
运行如下 Artisan 命令填充 posts 数据表了:
php artisan db:seed --class=PostsTableSeeder
创建我们的第一个 Article 模型及其对应迁移文件了,我们在项目根目录运行如下 Artisan 命令一步到位
php artisan make:model Article -m
编辑默认生成的迁移文件:
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');
}
}
运行如下命令创建对应数据表:
php artisan migrate
边栏推荐
- Beijiafu (p+f) R2000 modified radar IP
- Panorama of enterprise power in China SSD industry
- 结合源码剖析Oauth2分布式认证与授权的实现流程
- 京东618会议平板排行榜公布,新锐黑马品牌会参谋角逐前三名,向国货老大华为学习
- 2022年高处安装、维护、拆除考试模拟100题及模拟考试
- Research and investment strategy report on China's bridge anticorrosive coating industry (2022 Edition)
- Design and implementation of spark offline development framework
- Leetcode algorithm refers to offer II 027 Palindrome linked list
- EPICS record Reference 3 - - field available for all Records
- Based on the codeless platform, users deeply participated in the construction, and digital data + Nanjing Fiberglass Institute jointly built a national smart laboratory solution
猜你喜欢

shopee开店入驻流水如何提交?

Beijiafu (p+f) R2000 modified radar IP

2022年安全员-A证考题及答案

结合源码剖析Oauth2分布式认证与授权的实现流程

非单文件组件

Vulnhub Vegeta: 1

win10或win11打印机无法打印

2022-06-10 work record --js- obtain the date n days after a certain date

Introduction to machine learning compilation course learning notes lesson 1 overview of machine learning compilation

环境配置 | VS2017配置OpenMesh源码和环境
随机推荐
【nvm】
Research Report on market supply and demand and strategy of ceiling power supply device industry in China
go Cobra命令行工具入门
「ARM 架构」是一种怎样的处理器架构?
剑指 Offer 13. 机器人的运动范围
Talk about GC mechanism often asked in interview
The difference between get and post
[ROS play with turtle turtle]
AttacKG: Constructing Technique Knowledge Graph from Cyber Threat Intelligence Reports代码复现
Solve the problem of port occupation
The extra points and sharp tools are worthy of the trust | know that Chuangyu won the letter of thanks from the defense side of the attack and defense drill!
是否需要提高代码阅读能力?这有技巧
Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration
[text data mining] Chinese named entity recognition: HMM model +bilstm_ CRF model (pytoch) [research and experimental analysis]
MySQL kills 10 people. How many questions can you hold on to?
CDN principle
China solar window market trend report, technical dynamic innovation and market forecast
[QT] QT event handling
Feign project construction
Recommended course: workplace writing training