如何从Laravel中的对象获取数据

时间:2020-04-27 11:55:36

标签: laravel

View Code:

 <div class="content">
        <div class="title m-b-md">
            Pizza List - {{$id}}
        </div> 
        {{$p->type}}  // This is not working.Here I only want to print type of pizza from the 
                         db.ERROR 
                            =Property [type] does not exist on this collection instance.
        {{$p}}  // But This Does shows Data in JSON.
    </div>


Controller Code:

public function show($id){

        $p=Pizza::where('p_name','prashant')->get();

        return view('details',['id'=>$id,'p'=>$p]);
    }

在这里,我想由数据库中具有列名p_name的人获取披萨订单的类型,因此我给了一些静态名称。我只是一个初学者。任何人都可以告诉我如何打印仅比萨饼类型的

2 个答案:

答案 0 :(得分:0)

实际上,您正在使用show方法来获取数据,这表明您的控制器代码应如下所示:

public function show($id){
    $pizza = Pizza::where('p_name','prashant')->get()->first();
    return view('details')->with('pizza',$pizza);
}

您的视图代码应该是这样

<div class="content">
    <div class="title m-b-md">
        Pizza List - {{$pizza->id}}
    </div> 
    {{$pizza->type}}  // This Will work now
</div>

答案 1 :(得分:0)

如果您获得单个披萨值,请使用此

$p=Pizza::where('p_name','prashant')->first();


<div class="content">
    <div class="title m-b-md">
        Pizza List - {{$id}}
    </div> 
    {{$p->type}} 
</div>

如果您想要多个披萨值,请使用此

$p=Pizza::where('p_name','prashant')->get();

<div class="content">
    <div class="title m-b-md">
        Pizza List - {{$id}}
    </div> 
     @foreach($p as $pizza)
         {{$pizza->type}} 
     @endforeach
</div>