Blog スタッフブログ

Laravel システム開発

[Laravel]Modelのempty判定

システム開発担当のTFです。

やり方

  • find() や first() での1件取得は、 Model か null が返るのでPHP の empty 等で空判定する
  • get() や all() での複数件取得は、Collection が返る為、PHPの empty 等での判定はできず、Collection の isEmpty() 等で判定する

サンプル

<?php
	// idで取得 あれば Model, なければ null
	$test = Test::find(1);
	if( !empty($test) ){
		// 存在する
	}
	else{
		// 存在しない
	}
	
	// 取れた最初を取得 あれば Model, なければ null
	$test = Test::orderBy('created_at','desc')->first();
	if( !empty($test) ){
		// 存在する
	}
	else{
		// 存在しない
	}
	
	// 複数取得 あってもなくても Collection が返る
	$tests = Test::where('kind', 1)->get();
	if( $tests->isNotEmpty() ){
		// 存在する
	}
	else{
		// 存在しない
	}
	
	// 複数取得 あってもなくても Collection が返る
	$tests = Test::all();
	if( $tests->isNotEmpty() ){
		// 存在する
	}
	else{
		// 存在しない
	}