如何修复Laravel 5.7中的未定义变量ID错误

时间:2019-04-29 10:38:14

标签: php firebase laravel-5

M正在研究一种解决方案,其中我需要根据ID将数据从控制器传递到视图。

我已经逐个测试了每个变量,以查看这些变量中是否包含实际数据。

一旦我注释掉var_dumps(),

就会一一生成所需的所有值。引发未定义的索引错误。

请参见下面的代码:

查看

<td>
   <a href="view-campaign/{{$item->id}}" class="btn btn-success mb-2"
      data-toggle="tooltip" title="view campaign">                            
        <i class="fa fa-eye"></i>
   </a>
</td>

控制器

public function viewCampaign($id){

        //return var_dump($id);

        $img = null;

        //firebase configs and send to firebase
        $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
        $firebase = (new Factory)
            ->withServiceAccount($serviceAccount)
            ->withDatabaseUri('https://projectName.firebaseio.com/')
            ->create();

            $database = $firebase->getDatabase();

            $ref = $database->getReference('CampaignCollection')->getValue();

            foreach($ref as $key){
                $item = $key['id'];
                //return var_dump($item); 
                $poster = $key['Poster'];
                //return var_dump($poster); 
                if($item = $id){ 

                    //return '1';
                    $img = $poster; 
                    //return var_dump($poster);
                }else{
                    return '0';
                }
             }
        return view('view-campaign')->with('img',$img);
    }

路线

Route::get('view-campaign/{id}','CampaignController@viewCampaign');

View :: Results

@extends('layouts.layout')

@section('content')
<div class="col-md-12">
        <div class="col-md-12 panel">
            <div class="col-md-12 panel-heading">
                <h4>View Campaign:</h4>
            </div>
            <div id="imgContainer" class="col-md-12 panel-body">
               <a href="/listCampaign" class="btn btn-danger mb-2" style="margin-bottom: 15px"><i class="fa fa-arrow-circle-left"></i></a>
               @if(isset($img))
                  <div  align="center">
                    <img src="{{($img)}}" />
                  </div>
                @else
                  no data 
                @endif

            </div>    
        </div>
</div>
@endsection

目标是使base64代码传递给视图。

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码替换您的foreach:

foreach($ref as $k1 => $key){
                $item = $key->id; //change over here
                //return var_dump($item); 
                $poster = $key->Poster;  //change over here
                //return var_dump($poster); 
                if($item == $id){ //change over here

                    //return '1';
                    $img = $poster; 
                    //return var_dump($poster);
                }else{
                    return '0';
                }
             }

我认为,您还必须将函数签名更新为如下所示:

public function viewCampaign(Request $request , $id){
            //your code
}