Reputation: 45
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 class="form-group" 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
Upvotes: 2
Views: 644
Reputation: 45
is it possible to continue the error because I want to display in components.hero where is another controller? this is my web.php....
Route::get('/', [Controllers\ListingController::class, 'index']) ->name('listings.index');
and i have others views in this controller
UPDATE*
if I use diff. the route in web.php it's works
Route::get('/search', [Controllers\CitiesController::class, 'index']);
-> displaying cities from DB
Upvotes: 0
Reputation: 113
I read the comment i find out that you are trying another way to get the data. So you can do it like this.
<?php
namespace App\Http\Controllers;
use App\Models\City;
use Illuminate\Http\Request;
class CitiesController extends Controller
{
private $city;
public function __construct() {
$this->city = new City();
}
public function index(Request $request) {
$cities = $this->city->query()->orderBy('name')->get();
return view('<components.hero')->with('cities', $cities);
}
}
And in the view:
<select class="form-group" id="s" name="s">
<option value=""></option>
@foreach ($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
@endforeach
</select>
Upvotes: 0
Reputation: 17556
You pass in your code city as class membervariable but previously you assign only to $city.
Change this line: $this->view('<components.hero')->with('city', $this->city);
to view('components.hero')->with('city',$city);
. What you already had a line above ;-)
You can also pass Vars to your blade like that:
view('components.hero', ['city' => $city];
Upvotes: 0
Reputation: 506
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'));
}
Upvotes: 2
Reputation: 1304
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 class="form-group" id="s" name="s">
<option value=""></option>
@foreach ($cities as $city)
<option value="{{$city->id}}">{{$city->name}}</option>
@endforeach
</select>
Upvotes: 2