2016-02-04 71 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