作为程序员一定要保持良好的睡眠,才能好编程

laravel搭建api项目基础调整

发布时间:2019-05-24

现在需要使用laravel开发一个api后台项目,全部采用接口的形式开发,系统基础设施需要做什么?


https://www.jianshu.com/p/1bae1d6a03b2

ajax请求laravel的api接口


https://learnku.com/laravel/t/8783/exception-handling-in-laravel

Laravel 中的异常处理





https://blog.csdn.net/qq_35401605/article/details/82344360

laravel实现错误统一处理



https://blog.csdn.net/weixin_33670713/article/details/87471325

laravel中POST请求交互(前后端分离)/laravel去除csrf令牌验证







https://blog.csdn.net/pharaoh_shi/article/details/79418172

Laravel 开发 RESTful API 的一些心得

1.数据库查询

怎么统计一篇文章有多少评论?最快的方法是:

$article = Article::where('id',1)->withCount('comments')->first();
这样$article变量就有一个属性comments_count了:

$post->comments_count;
但是工作中可能会有这样以这个场景:获取点赞数大于的666的评论个数怎么办?这样:

$article = Article::where('id',1)->withCount('comments',function($query){
       $query->where('like', '>', 666);
   })->first();
2.多态关联
文章可以有评论,页面可以有评论,评论也可以有评论,
但是总不能建三张评论表吧?如果自己写条件判断也太麻烦了吧。。。Laravel的多态关联上场了!!这个地方的原理与JAVA中的多态类似。

//1.第一步在Comment模型中说明我是可以多态的
public function commentable()
{
    return $this->morphTo();
}

//2.在想要评论的模型中增加comments方法,
public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

//3.使用,就像普通的一对多关系一样,有点像JAVA中的的运行时绑定:
$model->comments;
原理很简单,comments表中增加两个列就行:

Schema::create('comments', function (Blueprint $table) {
     ***************省略*******************
     $table->morphs('commentable');
     //等价于
     $table->integer('commentable_id')->index();
     $table->string('commentable_type')->index();
    ****************省略******************
});
然后 laravel 会自动维持这些关系。注意,保存的评论的时候是有小技巧的,你的表单中至少要传两个参数:commentable_id和commentable_type:

$comment = new Comment();

$commentable_id = $request->get('commentable_id');
//commentable_type取值例如:App\Post,App\Page等等,也可以在 AppServiceProvider 中的 boot 函数中使用 Relation::morphMap 方法注册「多态映射表」,或者使用一个独立的服务提供者注册。

$commentable = app($request->get('commentable_type'))->where('id', $commentable_id)->firstOrFail();

****************省略******************

$commentable->comments()->save($comment);
保存评论的时候并不知道是谁的评论,而是使用容器根据commentable_type生成一个模型实例,这样也就和具体的模型解耦了,你可以让任何东西可以评论,而不需要修改代码,有点像面向对象设计原则中的OCP(开放-封闭原则 )。
---------------------


访问频率限制中间件throttle的使用

https://laravelacademy.org/post/3566.html




token

https://laravelacademy.org/post/9153.html#toc_12