skip to Main Content

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


  1. The error likely occurs because you’re trying to use the $tag variable directly in the Blade component without passing it correctly from the jobs.index. In your controller, you’re passing tags as an array, so you need to loop through tags and pass each tag to the component individually.

    Here’s how you can fix it:

    1. Update the View (jobs.index): Make sure you loop through the tags array and pass each tag item to the component.

      @foreach($tags as $tag)
      <a href="/tags/{{strtolower($tag->name)}}" class="{{ $classes }}">{{$tag->name}}</a>
      @endforeach
      
    2. Update the Component Usage: Since $tag is now passed as a prop, it should be defined correctly.

    Login or Signup to reply.
  2. 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.

    @props(['size' => 'base', 'tags'])
    
    @foreach ($tags as $tag)
    <a href="/tags/{{ strtolower($tag->name) }}" class="{{ $classes }}">{{ $tag->name }}</a>
    @endforeach
    
    1. Added tags as a prop in your Blade template.
    2. Used a @foreach loop to iterate over each $tag and generate the links.
    3. Verify that your Tag model is correctly set up and that it has a name attribute
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search