1

I have a problem with my Laravel project in using blade component.

When I define a new component and want to use "Component public Methods" to pass data to "view component blade file", I receive an error, "Undefined variable"

The component has been made by

php artisan make:component testc 

and i try

cache:clear

view:clear

and composer dump before

and has following codes:

component code

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class testc extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.testc');
    }

    public function test()
    {
        return 'test';
    }
}

view component blade file

<div>
    {{ $test }}
</div>

and my error

enter image description here

ps: laravel version is : 7.18.0

Mohammad
  • 652
  • 1
  • 7
  • 18
  • From that [page you linked](https://laravel.com/docs/7.x/blade#passing-data-to-components): "_You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view._" Your component class doesn't have any public properties – brombeer Jul 07 '20 at 12:01
  • @kerbh0lz not exactly when you should pass data to your component you need to define variable in constructor method but when you pass data to blade any public methods or variable can be accessible on component's balde – Mohammad Jul 07 '20 at 12:29
  • I am wondering that this even works, don't you get an `include(...app/View/Components/Testc.php): failed to open stream: No such file or directory` error because your component is `testc` and not `Testc`? – brombeer Jul 07 '20 at 13:12
  • @kerbh0lz hey bro have any idea to fix it , i have problem again look at https://github.com/laravel/framework/discussions/33454 – Mohammad Jul 07 '20 at 22:57
  • Please post a new question for a new problem – brombeer Jul 08 '20 at 06:19

1 Answers1

2
  • In your blade file you should call the method of your component like this:
<div>
   {{ $test() }}
</div>
  • Notice the brackets.
Emma
  • 27,428
  • 11
  • 44
  • 69
Tamás Kis
  • 31
  • 1
  • 3