我有数据存储在表格中我需要将数据显示到数据表中, 它抛出一个错误我不知道它是什么,请帮助我是laravel的新手,在我的其他项目中使用了这个代码,但它不适用于此 它在索引文件中特别在数据表部分
中抛出错误未定义的变量分支索引
<div class="row">
<div class="col-12">
<div class="card m-b-30">
<div class="card-body">
<h4 class="mt-0 header-title">Branch Details</h4>
<p class="text-muted m-b-30 font-14">
</p>
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>Company</th>
<th>Dealership</th>
<th>Branch Name</th>
<th>Age</th>
</tr>
</thead>
<?php $i = 1; ?>
<tbody>
@foreach($branch as $branch)
<tr>
<td>{{ $i }}</td>
<?php
$del=Dealership::where('dlr_id',$branch->dlr_id)->first();
?>
<td>{{$del->dlr_id}}</td>
<?php
$com=Company::where('comp_id',$branch->comp_id)->first();
?>
<td>{{$com->comp_id}}</td>
<td>{{$branch->name}}</td>
<td><a href="{{route('branch.edit',$branch->id)}}"><img src="assets/images/edit.png" class="imgsize"></a> </td>
<td><a href="{{route('branch.delete',$branch->id)}}"><img src="assets/images/delete.png" class="imgsize"></a></td>
</tr>
<?php $i++;?>
@endforeach
</tbody>
</table>
</div>
控制器文件
类BranchController扩展了Controller {
public function index()
{
$companies=Company::where('status','0')
->get();
$dealership=Dealership::where('status','0')->get();
$branch=Branch::where('status','0')->get();
return view('branch.index',['companies'=>$companies],['dealership'=>$dealership],['branch'=>$branch]);
}
public function store(Request $request)
{
$branch_id = new Branch;
$branch_id=Branch::orderBy('br_id','desc')->take(1)->get();
if(count($branch_id)>0)
{
$id= $branch_id[0]->br_id;
$id=$id+1;
}
else
{
$id=1;
}
$branch = new Branch;
$branch->br_id=$id;
$branch->name= $request->input('branch');
$branch->dlr_id= $request->input('dealer');
$branch->comp_id= $request->input('compnay');
$branch->created_id= '0';
$branch->save();
return redirect()->back()->with('message', 'Successfully saved');
}} }
模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Branch extends Model
{
//
protected $fillable=[
'br_id',
'name',
'dlr_id',
'created_id',
'status',
'comp_id'
];
public function company()
{
return $this->belongsTo('App\Company');
}
public function dealership()
{
return $this->belongsTo('App\Dealership');
}
public function employees()
{
return $this->hasMany('App\Employee');
}
}
答案 0 :(得分:0)
您将三个不同的数组传递给view
方法,而不是一个包含所有选项的数组。此外,在您的视图中,您对分支集合使用与单个分支(branch
)相同的名称,这会导致命名冲突。
在您的Controller的index
方法中,请改用:
$branches = Branch::where('status','0')->get();
return view('branch.index',['companies'=>$companies, 'dealership'=>$dealership, 'branches'=>$branches]);
在foreach
刀片指令中,使用新的$branches
变量:
@foreach ($branches as $branch)
<!-- ... -->
@endforeach
如果向视图添加大量变量,您可能会发现使用compact
方法更容易,更易读:
return view('branch.index', compact('companies', 'dealership', 'branches'));
只要定义了变量$companies
,$dealership
和$branches
,就会创建与上面相同的数组。