Home > other >  Laravel collection display and short issue
Laravel collection display and short issue

Time:10-16

Hello guys!


I have a a little problem with collections. I have never worked with these. I would like to display a collection at my welcome blade but there is a problem. My collection is not in the contrroller, the collection's place is in the App/Repositories/xyz.php and in a function. How can i pass this function to the controller and after show it at the welcome blade??

App/repositories/xyz.php

public function getcars(): Collection
    {
        
        return collect([
               new Car(...)
)];

controller

 public function __invoke(): View
    {
        return view('welcome', ['cars' => collect([
            new Car() ------> I would like to put datas from xyz.php repo here 
            new Car()
            new Car()
            ....

And welcome.blade file where i would like to display

<div class="car-list">
    <h2>{{ $title }}</h2>
    @foreach($cars as $car)
        <x-car :car="$car" />
    @endforeach
</div>

CodePudding user response:

I believe from your Controller file, you can create an object property of your Repository via __construct() method like this:

protected MyRepository $myRepository;

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

Then, you can call $this->myRepository's method from there, for example like getting records, etc. Then you can pass the result to your view.

CodePudding user response:

You could do that in many ways:

Creating new instance

use App\repositories\Xyz;

public function __invoke(): View
{
    $repo = new Xyz();
    
    return view('welcome')->with('cars', $repo->getcars());
}

Pulling your class from the container

use App\repositories\Xyz;

public function __invoke(): View
{
    $repo = app(Xyz::class);
    
    return view('welcome')->with('cars', $repo->getcars());
}

Using dependency injection to resolve it from container

use App\repositories\Xyz;

protected Xyz $repo;

public function construct(Xyz $xyz): View
{
    $this->repo = $xyz;
}    

public function __invoke(): View
{   
    return view('welcome')->with('cars', $this->repo->getcars());
}
  • Related