Terix
Terix

Reputation: 1387

Laravel 5.5 nested controller and view

Let's say I have an "Contact" entity, and I have built with model, controller, views. All CRUD operation works. Now I want to add addresses to the contact. There may be more than address for the same contact, but each address belongs only to one contact. Any CRUD operation about an address is nested to a contact.

I have built the model, and so far so good. I have populated the database by hand and I want to implement the addresses.index nested to the contacts.show.

The Addresses controller method should be something like this:

public function index($ContactId)
{
    $addresses = Addresses::where("contact_id",$ContactId)->paginate(10);
    return view('addresses.index',compact('addresses',"$ContactId"))
        ->with('i', (request()->input('page', 1) - 1) * 5);
}

Now I want to build the view, but I'm lost, because I can't find any useful example or tutorial (or they are for a very old version)

Upvotes: 0

Views: 559

Answers (1)

user320487
user320487

Reputation:

I nest addresses completely within users, contacts, leads, companies, etc. including the view directories, so users.address.index would be the view path, for example.

The routes to access addresses are also nested. If it's a simple project with only user's having addresses, the url would be '/users/1/addresses` to list their addresses. A controller method to list the address would typically look like:

class AddressController {
    public function index(Request $request, User $user) {
        return view('users.addresses.index', ['addresses' => $user->addresses]);
    }
}

Resource routing makes this all easy, you only have two route file entries like so:

Route::resource('users', 'UserController');
Route::resource('users.addresses', 'AddressController');

If I have several models in an application that can have addresses, I make Address polymorphic and abstract out the above controller further.

https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations

Upvotes: 1

Related Questions