Laravel 使用技巧

Job允许脱离队列

只需在控制器中调用 $this->dispatchNow() 即可。

public function approve(Article $article)
{    $this->dispatchNow(new ApproveArticle($article));}

获取数据的方法

如果你有一个具有复杂数据结构的数组,例如带对象嵌套的数组,你可以使用 data_get() 助手函数配合通配符和「点」符号,来从嵌套数组或对象中检索值。

// 我们有如下数组
[ 0 => 
['user_id' =>'用户id1', 'created_at' => '时间戳1', 'product' => {object Product}, ...], 
  1 => 
['user_id' =>'用户id2', 'created_at' => '时间戳2', 'product' => {object Product}, ...], 
  2 => ...
]

// 现在我们想要获取其中全部的产品id,我们可以这样写:
data_get($yourArray, '*.product.id');
// 这样我们就获取了全部的产品 id [1, 2, 3, 4, 5, ...]

可以定时执行的事情

你可以安排 artisan 命令、作业类、可调用类、回调函数、甚至是 shell 脚本去定时执行

use App\Jobs\Heartbeat;

$schedule->job(new Heartbeat)->everyFiveMinutes();
$schedule->exec('node /home/forge/script.js')->daily();
use App\Console\Commands\SendEmailsCommand;

$schedule->command('emails:send Taylor --force')->daily();

$schedule->command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
}

数据库原始查询计算运行得更快

使用类似 whereRaw() 方法的 SQL 原始查询,直接在查询中进行一些特定于数据库的计算,而不是在 Laravel 中,通常结果会更快。 例如,如果您想获得注册后 30 天以上仍处于活跃状态的用户,请使用以下代码:

User::where('active', 1)
->whereRaw('TIMESTAMPDIFF(DAY, created_at, updated_at) > ?', 30)
->get();

保存时移除缓存

如果您有提供集合 posts 这样的缓存键,想在新增或更新时移除缓存键,可以在您的模型上调用静态的 saved 函数:

class Post extends Model
{
    // 存储或更新时移除缓存
    public static function boot()
    {
        parent::boot();
        static::saved(function () {
           Cache::forget('posts');
        });
    }
}

忽略 $fillable/$guarded 并强制查询

如果你创建了一个 Laravel 模板作为其他开发者的「启动器」, 并且你不能控制他们以后会在模型的 $fillable/$guarded 中填写什么,你可以使用 forceFill()

$team->update(['name' => $request->name])

如果 name 不在团队模型的 $fillable 中,怎么办?或者如果根本就没有 $fillable/$guarded, 怎么办?

$team->forceFill(['name' => $request->name])

在删除模型之前执行任何额外的操作

我们可以使用 Model::delete() 执行额外的操作来覆盖原本的删除方法

// App\Models\User.php

public function delete(){

    //执行你想要的额外操作

    //然后进行正常的删除
    Model::delete();
}

如何防止 property of non-object 错误

// 设定默认模型
// 假设你有一篇 Post (帖子) 属于一个 Author (作者),代码如下:
$post->author->name;

// 当然你可以像这样阻止错误:
$post->author->name ?? ''
// 或者
@$post->auhtor->name

// 但你可以在Eloquent关系层面上做到这一点。
// 如果没有作者关联帖子,这种关系将返回一个空的App/Author模型。
public function author() {
    return $this->belongsTo('App\Author')->withDefaults();
}
// 或者
public function author() {
    return $this->belongsTo('App\Author')->withDefault([
        'name' => 'Guest Author'
    ]);
}

关联关系中过滤查询

假如您想加载关联关系的数据,同时需要指定一些限制或者排序的闭包函数。例如,您想获取人口最多的前 3 座城市信息,可以按照如下方式实现:

$countries = Country::with(['cities' => function($query) {
    $query->orderBy('population', 'desc');
    $query->take(3);
}])->get();
原文地址:https://www.cnblogs.com/sgm4231/p/15507626.html