【问题标题】:Why is my code showing this error: Undefined Variable为什么我的代码显示此错误:未定义变量
【发布时间】:2021-10-04 03:13:45
【问题描述】:

我正在尝试迁移我的外键并以公司形式显示员工列表。为此:

1.My CompaniesController

    public function index(){
    $cat = Company::all();
    return view(view:'company/index')->with ('cat', $cat);
}
  1. 这是我的公司迁移节目:

     public function up() {
       Schema::create('company', function (Blueprint $table) {
         $table->id();
         $table->unsignedBigInteger('emp_id');
         $table->foreign('emp_id')->references('id')->on('employeee')->onUpdate('cascade')->onDelete('cascade');
         $table->string('companyname')->nullable();
         $table->string('connumber')->nullable();
         $table->string('addressline1')->nullable();
         $table->string('addressline2')->nullable();
         $table->string('contactnumber')->nullable();
         $table->string('suburb')->nullable();
         $table->string('state')->nullable();
         $table->string('postcode')->nullable();
         $table->string('image');
         $table->timestamps();
     });
    

    }

这是我的下拉菜单代码

    `<div class="col-md-6">
      <select name="">
      @foreach ($cat as $row )
     <option value="{{$row->id}}">{{$row->companyname}}</option>
        @endforeach
               </select>
                    </div>`

这是公司的管理员路线:

      Route::resource('/admin/companies', 'Admin\CompaniesController',['as'=>'admin']);

`

请帮帮我

【问题讨论】:

标签: laravel undefined-variable


【解决方案1】:
    // this is how to send the variable to the view
    public function index(){
       $cat = Company::all();
       return view('company/index', ['cat'=>$cat]);
    }

@foreach ($cat as $row)
   <option value="{{$row->id}}">{{$row->companyname}}</option>
@endforeach

【讨论】:

  • 返回视图(view:'company/index', ['cat'=>$cat]);在这个声明中它说不能在命名争论之后使用位置争论
  • return view('company/index', ['cat'=&gt;$cat]); 没有第二个视图
  • 我在那里编辑了我的解决方案,很抱歉。
  • 非常感谢它解决了我的问题,但你能帮我用外键吗
【解决方案2】:
    return view('company/index')->with('cat', $cat);

你可以试试。删除括号中的view 并删除空格with('cat', $cat);

【讨论】:

  • 非常感谢,但你能帮我用外键吗?迁移部分的代码对吗?我很困惑
  • 在公司模型中,您可以使用类似 *** public function employees(){ return $this->hasMany(Employee::class, 'id', 'employee_id');然后在控制器中写入 $cat = Company::with('employees')->get(); return view('company/index')->with('cat', $cat); ***
  • 在公司模型中,您可以使用public function employees(){ return $this-&gt;hasMany(Employee::class, 'id', 'employee_id'); } 之类的关系,然后在$cat = Company::with('employees')-&gt;get(); return view('company/index')-&gt;with('cat', $cat); 之类的控制器中写入
  • @BarshuMhzn 您的迁移很好。我不明白为什么您的公司名称列是nullable。您在下拉菜单上显示公司名称,因此如果您将其设置为 nullable,那么您最终将显示空白选项。
猜你喜欢
  • 2021-03-29
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多