29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

HTTP Controllers 73<br />

.<br />

17 {<br />

18 return view('user.profile', ['user' => User::findOrFail($id)]);<br />

19 }<br />

20 }<br />

We can route to the controller action like so:<br />

.<br />

1 Route::get('user/{id}', 'UserController@showProfile');<br />

Now, when a request matches the specified route URI, the showProfile method on the UserController<br />

class will be executed. Of course, the route parameters will also be passed to the method.<br />

Controllers & Namespaces<br />

It is very important to note that we did not need to specify the full controller namespace when<br />

defining the controller route. We only defined the portion of the class name that comes after<br />

the App\Http\Controllers namespace “root”. By default, the RouteServiceProvider will load the<br />

routes.php file within a route group containing the root controller namespace.<br />

If you choose to nest or organize your controllers using PHP namespaces deeper into the App\Http\Controllers<br />

directory, simply use the specific class name relative to the App\Http\Controllers root namespace.<br />

So, if your full controller class is App\Http\Controllers\Photos\AdminController, you would<br />

register a route like so:<br />

.<br />

1 Route::get('foo', 'Photos\AdminController@method');<br />

Naming Controller Routes<br />

Like Closure routes, you may specify names on controller routes:<br />

.<br />

1 Route::get('foo', ['uses' => 'FooController@method', 'as' => 'name']);<br />

Once you have assigned a name to the controller route, you can easily generate URLs to the action. To<br />

generate a URL to a controller action, use the action helper method. Again, we only need to specify<br />

the part of the controller class name that comes after the base App\Http\Controllers namespace:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!