laravel variable not reading from mysql

73 views Asked by At

I've come back to a Laravel project having been away from coding to deal with a personal situation. Now I've hit a brick wall. I'm getting an "Undefined variable" error which I don't know how to fix. This was working perfectly two months ago, I don't understand why it's not working now.

When I remove the @foreach and MySQL reading from the component, the error message goes away and I'm left with the empty template. I'm taking it as a problem reading from the database.

Here is the error message:

HTTP 500 Internal Server Error

Undefined variable $jobs (View: /Users/macUser/Desktop/new-app/resources/views/pages/about.blade.php)

new-app/storage/framework/views/bf7b3742a5b2f32d56326224b3c2159e.php:110

withAttributes(['jobs' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($jobs)]); ?>renderComponent(); ?>

Here is the code:

views/pages/about.blade.php

<x-section>

    <x-subtitle subTitle="Areas of Speciality" />

    <x-jobs :jobs="$jobs"/>

</x-section>

views/components/jobs.blade.php

@foreach ($jobs as $job)

<div class="tile is-parent is-4">

    <div class="tile is-child">

        <h4 class="is-size-4 has-text-weight-semibold my-2">
            <span class="icon is-purple mr-4"><i class="{{ $job->icon }} "></i></span><br>
            {{ $job->jobTitle }}
            <div class="divider my-2"></div> 
        </h4>
        <p class="is-size-6 is-wordy"> {{ $job->description }} </p>

    </div><!-- is-child -->
</div><!-- is-parent -->

@endforeach

app/View/Components/Jobs.php

<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class Jobs extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.jobs');
    }
}

Patience appreciated

1

There are 1 answers

0
Khayam Khan On

To some extent, I understand why $jobs is giving you error because you are not accepting the $jobs in your component class.

Update your component class and accept this $jobs.

<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class Jobs extends Component
{
    public $jobs;

    /**
     * Create a new component instance.
     */
    public function __construct($jobs)
    {
        $this->jobs = $jobs;
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.jobs');
    }
}