如何在laravel的下拉选项字段中显示值?

时间:2018-07-25 05:51:16

标签: php html5 css3 laravel-5 bootstrap-4

我有3个表主机 访问者 visitor_types 。我想在下拉选项按钮中显示主机名访客类型。但是我对 controller route 代码有些困惑。我写了下面给出的代码,但显示了-Undefined变量:host (视图:C:\ laragon \ www \ ves \ resources \ views \ admin \ visitor.blade.php)

Controller Code: VisitorController.php


  <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Visitor;
use App\Host;
use App\visitorType;
use App\visitors;
use App\hosts;
use App\visitorTypes;
use App\visitor_s;

class VisitorController extends Controller
{
    public function __construct(){
        $this->middleware("auth");
    }
    // View All Visitor
public function index() {

    $visitor = Visitor::all();
    return view('admin\visitor', compact('visitor'));
}
// Taking all host data
public function optionValue() {
    $hosts = Host::all();
    return view('admin\host', compact('hosts'));
}


    Model : Visitor.php
    <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Visitor extends Model
{
//
public function hosts(){
    return $this->belongsTo('App\Host');
}
public function visitorTypes(){

    return $this->hasMany('App\VisitorType');
}
}

Model: Host.php




  <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Host extends Model
{
//
public function visitors(){
    return $this->hasMany('App\Visitor');
}

}

View Code: visitor.blade.php

<select class="form-control input-medium" name="host">
  @foreach($hosts as $host)
   <option value="{{ $host->name }}">{{ $host->name}}</option>
  @endforeach

Route code: web.php
Route::get('/vsistor','VisitorController@optionValue')->name('optionValue');

在visitor表中, host_id vType_id host 和visitor_types表中的外键。  那么,如何在下拉按钮中显示来自另一个表的名称

2 个答案:

答案 0 :(得分:0)

有两个错误。

1)您发送了$ host变量进行查看,但在视图的foreach循环中将其用作$ hosts。 您可以将代码设置为此

$hosts = host::all();
return view('admin\visitor', compact('hosts'));

2)您必须使用{{}}在视图上打印变量。

<option value="{{ $host->name }}">{{ $host->name}}</option>

Ps:实际上,型号名称必须以大写字母开头(host :: all()-> Host :: all())

答案 1 :(得分:0)

公共功能index(){

$visitor = Visitor::all();
$hosts = Host::all();
$visitorType = VisitorType::all();
return view('admin\visitor', compact('hosts','visitorType','visitor'));

}