Laravel 9个不经常用的小技巧

时间:2022-06-20
本文章向大家介绍Laravel 9个不经常用的小技巧,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 更新父表的timestamps

如果你想在更新关联表的同时,更新父表的timestamps,你只需要在关联表的model中添加touches属性。 比如我们有PostComment两个关联模型

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Comment extends Model
{
    /**
     * 要更新的所有关联表
     *
     * @var array
     */
    protected $touches = ['post'];

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

2. 懒加载指定字段

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

3. 跳转指定控制器并附带参数

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

4. 关联时使用withDefault()

在调用关联时,如果另一个模型不存在,系统会抛出一个致命错误,例如 $comment->post->title,那么我们就需要使用withDefault()

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

5. 两层循环中使用$loop

bladeforeach中,如果你想获取外层循环的变量

@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. 浏览邮件而不发送

如果你使用的是mailables来发送邮件,你可以只展示而不发送邮件

Route::get('/mailable', function () {
    $invoice = AppInvoice::find(1);
    return new AppMailInvoicePaid($invoice);
});

7. 通过关联查询记录

hasMany关联关系中,你可以查询出关联记录必须大于5的记录

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

8. 软删除

查看包含软删除的记录

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

查看仅被软删除的记录

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

恢复软删除的模型

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

9. Eloquent时间方法

<span type="button" created_at',="" '2018-01-31')-="" style="box-sizing: border-box;">get(); $posts = Post::whereMonth('created_at', '12')->get(); $posts = Post::whereDay('created_at', '31')->get(); $posts = Post::whereYear('created_at', date('Y'))->get(); $posts = Post::whereTime('created_at', '=', '14:13:58')->get();" title="">

$posts = Post::whereDate('created_at', '2018-01-31')->get(); 
$posts = Post::whereMonth('created_at', '12')->get(); 
$posts = Post::whereDay('created_at', '31')->get(); 
$posts = Post::whereYear('created_at', date('Y'))->get(); 
$posts = Post::whereTime('created_at', '=', '14:13:58')->get();