PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Can multi word variable be passed to blade component?

 February 12, 2022     laravel, laravel-8, laravel-blade     No comments   

Issue

I have created new component using php artisan make:component Test. Now, when creating that component, if I try to pass one word variable everything works fine (<x-test :testID="'test'"). But when I try passing it as multi word, separating words by using underscore (<x-test :test_id="'test'"), I am facing next error:

Unresolvable dependency resolving [Parameter #0 [ <required> $test_id ]] in class App\View\Components\Test 

And that class looks like this:

class Test extends Component
{
    public $test_id;

    public function __construct($test_id)
    {
        $this->test_id = $test_id;
    }

    public function render()
    {
        return view('components.test');
    }
}

Is this normal behaviour and is it even allowed to use underscore when creating variables inside components?


Solution

Livewire components do not support the classical __construct constructor. Instead you better use the mount() method.

Furthermore you should work with public properties like this

public $test_id;

public function mount()
{
    // properly initialize the var
    $this->test_id = 0;
}

and reference (see Data Binding) it in your view with

<x-test wire.model="test_id"/>

I generally would always go for camelCase naming, f. ex. testId. This is definately fully supported in Livewire (see docs).

Some general hint about naming variables

What you describe with one word and multi word variable is named

  • camel case, f. ex. myVariableName, Wikipedia
  • snake case, f. ex. my_variable_name, Wikipedia

Update for comment component

class Comments extends Component
{
    public int $postId;

    public function mount()
    {
        $this->postId = 0;
    }


    public function render()
    {
        $comments = Comments::where('post_id', $this->postId)->get();

        return view('post.list', [
          'comments' => $comments,
        ]);
    }
}

In your views you can use something like this.

<x-comments :postId="$post->id"/>

You don't need to inject it into the mount method. Just use the public property.



Answered By - codedge
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing