I started to learn Laravel a couple a days ago but I have error in code somewhere where it says that $tag variable is undefined, my Blade template is below:
@props(['tag','size'=>'base'])
@php
$classes = "bg-white/10 hover:bg-white/25 rounded-xl font-bold transition-colors duration-300";
if ($size === 'base') {
$classes .= " px-5 py-1 text-sm";
}
if ($size === 'small') {
$classes .= " px-3 py-1 text-2xs";
}
@endphp
<a href="/tags/{{strtolower($tag->name)}}" class="{{ $classes }}">{{$tag->name}}</a>
In the JobController.php:
<?php
namespace AppHttpControllers;
use AppModelsTag;
use AppModelsJob;
use AppHttpRequestsStoreJobRequest;
use AppHttpRequestsUpdateJobRequest;
class JobController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$jobs = Job::all()->groupBy('featured');
return view('jobs.index', [
'featuredJobs' => $jobs[0],
'jobs' => $jobs[1],
'tags' => Tag::all(),
]);
}
}
2
Answers
The error likely occurs because you’re trying to use the
$tag
variable directly in the Blade component without passing it correctly from thejobs.index
. In your controller, you’re passingtags
as an array, so you need to loop throughtags
and pass each tag to the component individually.Here’s how you can fix it:
Update the View (
jobs.index
): Make sure you loop through thetags
array and pass eachtag
item to the component.Update the Component Usage: Since
$tag
is now passed as a prop, it should be defined correctly.In your JobController, you’re retrieving all tags with
Tag::all()
, but it looks like you’re not actually passing the$tags
variable to your Blade template when rendering it.