Home > Mobile >  Passing variable from controller in components/blade
Passing variable from controller in components/blade

Time:04-18

i have this situation.

Undefined variable: city (View: \newjoblist\resources\views\components\hero.blade.php)

in my controller i have

<?php

namespace App\Http\Controllers;

use App\Models\City;
use Illuminate\Http\Request;

class CitiesController extends Controller
{
    
    public function index(Request $request){

        $city = City::orderBy('name') // variable displayed in view
        ->get();
        

        // return view('components.hero')->with('city',$city);
        $this->view('<components.hero')->with('city', $this->city);

    }
}

and in components/hero.blade.php

<select  id="s" name="s">
                        <option value=""></option>
                        @foreach ($city as $cities)
                        <option value="{{$cities}}">{{$cities->name}}</option>
                       
                        @endforeach
                      </select>

i don't know if i need to do something in web.php

CodePudding user response:

You can also do this

public function index(Request $request)
{
   $cities = City::orderBy('name') // variable displayed in view
   ->get();
   return view('components.hero', compact($cities));
}

CodePudding user response:

you need to update your index method to

public function index(Request $request){

        $cities = City::orderBy('name') // variable displayed in view
        ->get();
        

         return view('components.hero')->with('cities',$cities);

    }

and at the view

<select  id="s" name="s">
                        <option value=""></option>
                        @foreach ($cities as $city)
                        <option value="{{$city->id}}">{{$city->name}}</option>
                       
                        @endforeach
                      </select>
  • Related