前言

众所周知laravel是一套简洁、优雅的php web开发框架(php web framework)。下面这篇文章主要给大家总结了一些laravel不经常用的小技巧,下面话不多说了,来一起看看详细的介绍吧

1. 更新父表的timestamps

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

<?php

namespace app;

use illuminate\database\eloquent\model;

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

 /**
  * get the post that the comment belongs to.
  */
 public function post()
 {
  return $this->belongsto('app\post');
 }
}

2. 懒加载指定字段

$posts = app\post::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(app\post::class)->withdefault();
}

5. 两层循环中使用$loop

在blade的foreach中,如果你想获取外层循环的变量

@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 = app\invoice::find(1);
 return new app\mail\invoicepaid($invoice);
});

7. 通过关联查询记录

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

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

8. 软删除

查看包含软删除的记录

$posts = post::withtrashed()->get();

查看仅被软删除的记录

$posts = post::onlytrashed()->get();

恢复软删除的模型

post::withtrashed()->restore();

9. eloquent时间方法

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对www.887551.com的支持。