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.

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?