当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel中9个不经常用的小技巧汇总

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-19 10:10:50 浏览: 评论:0 

这篇文章主要给大家总结介绍了关于Laravel中9个不经常用的小技巧,文中通过示例代码介绍的非常详细,对大家学习或者使用Laravel具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。

前言

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

1. 更新父表的timestamps

如果你想在更新关联表的同时,更新父表的timestamps,你只需要在关联表的model中添加touches属性。

比如我们有Post和Comment两个关联模型

  1. <?php 
  2.  
  3. namespace App; 
  4.  
  5. use Illuminate\Database\Eloquent\Model; 
  6.  
  7. class Comment extends Model 
  8.  /** 
  9.   * 要更新的所有关联表 
  10.   * 
  11.   * @var array 
  12.   */ 
  13.  protected $touches = ['post']; 
  14.  
  15.  /** 
  16.   * Get the post that the comment belongs to. 
  17.   */ 
  18.  public function post() 
  19.  { 
  20.   return $this->belongsTo('App\Post'); 
  21.  } 

2. 懒加载指定字段

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

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

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

4. 关联时使用withDefault()

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

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

5. 两层循环中使用$loop

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

  1. @foreach ($users as $user)   
  2.  @foreach ($user->posts as $post)    
  3.  @if ($loop->parent->first)     
  4.   This is first iteration of the parent loop.    
  5.  @endif  
  6.  @endforeach 
  7. @endforeach 

6. 浏览邮件而不发送

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

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

7. 通过关联查询记录

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

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

8. 软删除

查看包含软删除的记录

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

查看仅被软删除的记录

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

恢复软删除的模型

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

9. Eloquent时间方法

  1. $posts = Post::whereDate('created_at''2018-01-31')->get();  
  2. $posts = Post::whereMonth('created_at''12')->get();  
  3. $posts = Post::whereDay('created_at''31')->get();  
  4. $posts = Post::whereYear('created_at'date('Y'))->get();  
  5. $posts = Post::whereTime('created_at''=''14:13:58')->get();

Tags: Laravel小技巧

分享到: