Summary of 9 infrequent tips in Laravel

  • 2021-12-09 08:22:32
  • OfStack

Preface

As we all know, Laravel is a simple and elegant PHP Web development framework (PHP Web Framework). The following article mainly summarizes some tips that Laravel doesn't often use. Let's not say much below. Let's take a look at the detailed introduction

1. Update the timestamps of the parent table

If you want to update the parent table's timestamps as well as the associated table, you only need to add the touches attribute to the associated table's model.
For example, we have two association models, Post and Comment


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
 /**
  *  All associated tables to update 
  *
  * @var array
  */
 protected $touches = ['post'];

 /**
  * Get the post that the comment belongs to.
  */
 public function post()
 {
  return $this->belongsTo('App\Post');
 }
}

2. Load specified fields lazily


$posts = App\Post::with('comment:id,name')->get();

3. Jump the specified controller with parameters


return redirect()->action('SomeController@method', ['param' => $value]);

4. Use withDefault () when associating

When the association is invoked, if another model does not exist, the system throws a fatal error, such as $comment- > post- > title, then we need to use withDefault ()


...
public function post()
{
 return $this->belongsTo(App\Post::class)->withDefault();
}

5. Use $loop in a two-tier loop

In foreach of blade, if you want to get the variables of the outer loop,


@foreach ($users as $user)  
 @foreach ($user->posts as $post)   
 @if ($loop->parent->first)    
  This is first iteration of the parent loop.   
 @endif  
 @endforeach 
@endforeach

6. Browse email without sending

If you are using mailables to send mail, you can just show and not send mail


Route::get('/mailable', function () {
 $invoice = App\Invoice::find(1);
 return new App\Mail\InvoicePaid($invoice);
});

7. Query records by association

In an hasMany association, you can find records whose association record must be greater than 5


$posts = Post::has('comment', '>', 5)->get();

8. Soft Delete

View records containing soft deletions


$posts = Post::withTrashed()->get();

View records that are only softly deleted


$posts = Post::onlyTrashed()->get();

Restore the model of soft deletion


Post::withTrashed()->restore();

9. Eloquent Time Method


$posts = App\Post::with('comment:id,name')->get();
0

Summarize


Related articles: