2016-02-04 72 views
0

選擇查詢我想創建一個類似下面,在helper.php內我Laravel 5.1項目。創建一個自定義值的輔助方法在Laravel

$result = App\Pages::where('id', $id)->where('active', 1)->first();

這裏是我的helper.php的樣子:

<?php 
namespace App\Helpers; 
use App; 
class Helper 
{ 
     public static function checkSlug($subject, $id, $inputSlug = null){ 
      $result = App\$subject::where('id', $id)->where('active', 1)->first(); 
      return $result; 
     } 
} 
?> 

我的助手類似乎工作的罰款。但我卡在這一行App\$subject::where('id', $id)->where('active', 1)->first();。當我通過變量$subject我得到這個提示以下錯誤:

parse error, expecting `"identifier (T_STRING)"' 

而且這裏是我如何用我的觀點

{{Helper::checkSlug('Pages', $page->id)}}

現在我的helper方法,當我試圖訪問我的模型不允許使用App\$subject。我猜。

任何建議將有所幫助。謝謝!

回答

1

我的意思是你不能在靜態方法語法中使用變量類。但你可以實例化你的模型:

public static function checkSlug($subject, $id, $inputSlug = null) 
{ 
    $clsname = 'App\\' . $subject; 
    $cls = new $clsname(); 
    $result = $cls->where('id', $id)->where('active', 1)->first(); 
    return $result; 
} 

並與對象建立你的查詢並得到你的行或不。

+0

謝謝你的回覆。但是它在'$ cls = new {$ clsname}();' – user3201500

+0

上顯示'parse error'你有完整的分析錯誤嗎? –

+0

是的,這只是我得到的錯誤 – user3201500