dongyuqi3808 2017-03-16 05:53
浏览 292

如何在laravel View中调用方法?

I have controller which will load the view part

public function homePage(){
    $categories = Category::all();
    $products = Product::all();
    return view('cart.index',compact('categories','products'));
}

Here is the View (basically checking for subcategory if there it will show otherwise skip)

<ul class="list-group list-group-bordered list-group-noicon uppercase">
    <li class="list-group-item active">
        @foreach($categories as $row)
            <a class="dropdown-toggle" href="#">{{$row->name}}</a>
            @if({{StapsController::checkSubcategory($row->id)}})
                @foreach($subcategories as $sub)
                    <ul>                                        
                        <li><a href="#"><span class="size-11 text-muted pull-right">(123)</span> {{$sub->s_name}}</a></li>          
                    </ul>
                @endforeach 
            @else
                <li class="list-group-item"><a href="#"><span class="size-11 text-muted pull-right">(189)</span> {{$row->name}}</a></li>
            @endif
        @endforeach

    </li>
</ul>   

Here is the checkSubcategory method

public function checkSubcategory($id){
    $category = Category::find($id);
    $id = $category->id;
    $subcategories = DB::table ('subcategories')
        ->join('categories_subcategories','subcategories.id','=','categories_subcategories.subcategory_id')
        ->join('categories','categories_subcategories.category_id','=','categories.id')
        ->where('categories.id','=',$id)
        ->select('subcategories.name as s_name ')
        ->get(); 

    return $subcategories;
}

But i got syntax Error in line of calling method in View? what could be the error ..is there any mistake calling method in view part?

  • 写回答

6条回答 默认 最新

  • donglu9898 2017-03-16 06:08
    关注

    If the logic of checkSubcategory works fine in the controller itself, you have to transport it to the model. i.e make it model's method so from the view you could able to do something like the following:

    ....
    <a class="dropdown-toggle" href="#">{{$row->name}}</a>
                                            @if({{$row->checkSubcategory($row->id);}})
                                            <ul>
    ....
    

    In other words, define this method in your Category model.

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?