Laravel tips

The Job is allowed to leave the queue

Just call in the controller.  $ this->dispatchNow()   Just.

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

Method of obtaining data

If you have an array with complex data structures, such as an array with nested objects, you can use data_ The get() helper function works with wildcards and the dot symbol to retrieve values from nested arrays or objects.

// We have the following array
[ 0 => 
['user_id' =>'user id1', 'created_at' => 'Timestamp 1', 'product' => {object Product}, ...], 
  1 => 
['user_id' =>'user id2', 'created_at' => 'Timestamp 2', 'product' => {object Product}, ...], 
  2 => ...
]

// Now we want to get all of them id,We can write this:
data_get($yourArray, '*.product.id');
// So we get all the products id [1, 2, 3, 4, 5, ...]

 

Something that can be performed regularly

You can schedule artisan commands, job classes, callable classes, callback functions, and even shell scripts to execute regularly

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();
}

Database raw query calculations run faster

Using the original SQL query similar to the whereRaw() method, you can perform some database specific calculations directly in the query, rather than in Laravel, and the results are usually faster. For example, if you want to get users who are still active more than 30 days after registration, use the following code:

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

Remove cache on save

If you provide a collection   posts   For such cache keys, if you want to remove them when adding or updating, you can call the static key in your model   saved   Function:

class Post extends Model
{
    // Remove cache when storing or updating
    public static function boot()
    {
        parent::boot();
        static::saved(function () {
           Cache::forget('posts');
        });
    }
}

ignore  $ fillable/$guarded   And forced query

If you create a Laravel template as a "starter" for other developers, and you can't control what they will do in the future  $ fillable/$guarded   What can you fill in   forceFill()

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

If name is not in the team model  $ fillable   Yes, what should I do? Or if not at all  $ What about fillable/$guarded?

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

Perform any additional operations before deleting the model

We can use   Model::delete()   Perform additional operations to overwrite the original deletion method

// App\Models\User.php

public function delete(){

    //Perform the additional actions you want

    //Then delete normally
    Model::delete();
}

How to prevent   property of non-object   error

// Set default model
// Suppose you have a Post that belongs to an Author. The code is as follows:
$post->author->name;

// Of course, you can stop mistakes like this:
$post->author->name ?? ''
// perhaps
@$post->auhtor->name

// But you can Eloquent Do this at the relationship level.
// If no author is associated with the post, this relationship will return an empty App/Author model.
public function author() {
    return $this->belongsTo('App\Author')->withDefaults();
}
// perhaps
public function author() {
    return $this->belongsTo('App\Author')->withDefault([
        'name' => 'Guest Author'
    ]);
}

Filter query in association

If you want to load the data of association relationship, you need to specify some closure functions for restriction or sorting. For example, if you want to obtain information about the top three cities with the largest population, you can do so as follows:

$countries = Country::with(['cities' => function($query) {
    $query->orderBy('population', 'desc');
    $query->take(3);
}])->get();

Posted by curtisdw on Thu, 04 Nov 2021 08:20:54 -0700