1

I try to use trait in laravel blade, but didn't work.

This is trait

namespace App\Repositories;

trait Residence
{
    public $country=['USA','Japan','Italy'];

    public $building=['duplex','condominium'];
}

I try to use in my blade like this:

@inject('Residence', 'App\Repositories\Residence')

@foreach($Residence->country as $country)
    {{$country}}
@endforeach

@foreach($Residence->building as $building)
    {{$building}}
@endforeach

But I get Target [App\Repositories\Residence] is not instantiable. error, any suggestion?(I'm using laravel 5.7)

3
  • 3
    A trait is supposed to be used by a Class, i dont know why you try to load it in blade .. Commented Jan 2, 2019 at 8:44
  • Well the reason I do this, is because there are variables in the trait and I need to inject into a blade(as a component) Commented Jan 2, 2019 at 9:05
  • Since trait won't work,so I have to build another class. Commented Jan 2, 2019 at 9:06

1 Answer 1

9

Thank you @Louis R remind that "A trait is supposed to be used by a Class"

So I use the trait in a class, and inject into the blade, it works!

This is trait.

namespace App\Repositories;

trait Residence
{
    public $country=['USA','Japan','Italy'];

    public $building=['duplex','condominium'];
}

This is a class use the trait.

namespace App\Repositories;

Class ResidenceClassForBlade
{
    use Residence;
}

This is blade:

@inject('Residence', 'App\Repositories\ResidenceClassForBlade')

@foreach($Residence->country as $country)
    {{$country}}
@endforeach

@foreach($Residence->building as $building)
    {{$building}}
@endforeach
Sign up to request clarification or add additional context in comments.

9 Comments

Do you render this view via some class?
No. This is a component blade, which will call by other blade like this: @component(the-blade-which-inject-a-class)
So, the parent blade is rendered via class. Right?
In that case, you can make a base Controller class and add this trait into it and make every controller class extend(inherit) that class. This will avoid you some manual injection.
Base on the BaseController idea, I refactor like this: a class use the trait, and then I inject into the blade, and it works! And it's better than I change the trait to a class.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.