我正在尝试在helper.php中的Laravel 5.1项目中创建类似下面的内容。
$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;
}
}
?>
My Helper课似乎运作良好。但我被困在这一行App\$subject::where('id', $id)->where('active', 1)->first();
。当我传递变量$subject
时,我得到以下错误:
parse error, expecting `"identifier (T_STRING)"'
以下是我在视图中使用辅助方法的方法
{{Helper::checkSlug('Pages', $page->id)}}
现在,当我尝试使用App\$subject
访问我的模型时,它不允许。我想。
任何建议都会有所帮助。谢谢!
答案 0 :(得分: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;
}
并使用该对象构建您的查询并获取您的行。