user15522248
user15522248

Reputation: 13

How can I get data from multiple controllers into a Laravel Blade view?

I'm new with Laravel (and programming) and I'm a bit confused.

Using the Eloquent ORM I store in the database a list of pets and their info in a pets table with a Pet model and a Pet controller. I also have a users table with User model. Then I have an owner_pet table that contains foreing keys to user_id and pet_id, with an OwnerPet model and controller.

I have a view called 'pets' and I want there to be a form and a list of the user pets, only accesible by authenticated users.

I have this route:

 Route::get('/pets', [App\Http\Controllers\HomeController::class, 'index'])->name('pets');

There, using the auth middleware it checks the user is logged in and returns the view 'pets', that contains a form to add pets.

    public function __construct()
{
    $this->middleware('auth');
}

    public function index()
{
    return view('pets');
}

This works fine.

Then I have a pet controller with an add pet function, I use it with a form in the 'pets' view that calls this route:

Route::post('/add', 'PetController@addPet')->name('add');

When the pet is added I return the 'pets' view with a success message.

return view('pets')->with('success', $success);

This works fine.

Then I have a ownerPets index function where I get all the info I need and store it as $pets and call the 'list' view:

public function index()
{
    $ownerPets = OwnerPet::leftjoin('pets', 'pets.id', '=', 'owner_pets.pet_id')
    ->where('user_id', Auth::user()->id)->paginate(20);
    return view('list')->with('pets', $pets);
}

I call the function with this route:

Route::get('/list', 'OwnerPetController@index')->name('list');

This works fine, I can see the list of the user's pets.

But I need to have everything in the same view, and I can only call a single function from the route.

Do I need to make another controller and call all the functions from there and then send all the data to the view? I was told calling a controller from another controller was a bad practice, but I can't think of another way to do this.

Can I maybe make a view that contains the other 2 views? But I don't know how would I get the functions to pass the data to them.

Please I need some advice. Thanks.

Upvotes: 0

Views: 399

Answers (1)

Rithy Sam
Rithy Sam

Reputation: 41

This mean that you want a page which have add form at the right side and list of pet with owner information at the left (for example).

so, you just

  1. This Route::get('/list', 'OwnerPetController@index')->name('list'); will return list pet and add from for the same page.
  2. Create another route like Route::post('/add', 'PetController@addPet')->name('add'); (in the same controller or other controller, it up to you) for adding pet.
  3. after you fill up the form and click submit, addPet function must return view('pets');

Hope martch your question.

Thanks

Upvotes: 0

Related Questions