duanjiati1755 2016-02-04 20:38
浏览 15
已采纳

创建自定义值在Laravel中的辅助方法中选择查询

i am trying to create a something like below, in my Laravel 5.1 project within helper.php.

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

here is how my helper.php looks like:

<?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 class seems working fine. But i am stuck in this line App\$subject::where('id', $id)->where('active', 1)->first();. When i pass the variable $subject i get this below error:

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

And here is how i am using my helper method in my view

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

Now when i am trying to access my Model using App\$subject its not allow. I guess.

Any suggestions will be helpful. Thank you!

  • 写回答

1条回答 默认 最新

  • douyu5775 2016-02-04 20:55
    关注

    I mean you can't use variable classes with static methode syntax. But you can instantiate your model:

    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;
    }
    

    and with the object build your query and get your row or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效