Laravel : Structure and organize routes.php - php

I'm trying to use GET|POST|PUT|DELETE in my controllers.
I feel like my routes.php file is going to get messy as my project bigger and bigger, as I will have to register lots of routes for all the GET|POST... requests.
This is the structure I'm using now:
<?php
/*
|--------------------------------------------------------------------------
| Home Routes
|--------------------------------------------------------------------------
*/
//Get
Route::get('/', 'HomeController#getIndex');
Route::get('/home/logout', 'HomeController#getLogout');
//Post
Route::post('/home/login', 'HomeController#postLogin');
/*
|--------------------------------------------------------------------------
| Appointment Routes
|--------------------------------------------------------------------------
*/
//Get
Route::get('appointments', 'ApptController#getIndex');
Is there a better way to do this? How can I organize/improve this file?
Can you give me some advice? Thanks!

You can route incoming requests directly to your existing Controllers using the Route::controller() method in routes.php:
Route::controller('home', 'HomeController');
Route::controller('appointments', 'AppointmentsController');
Then all requests to home/* will go be handled by your HomeController, appointments/* will go to AppointmentsController etc etc etc.
It looks you have already created your functions in the Controller using the HTTP method, so then:
a HTTP GET to '/' will be handled by HomeController#getIndex()
a HTTP GET to 'logout' will be handled by HomeController#getLogout()
a HTTP POST to 'login' will be handled by HomeController#postLogin()
More in the excellent and eloquent Laravel docs here

There some ways you can improove your routes, in the case above, you can for example do this:
Route::group(array('prefix' => 'home'), function()
{
Route::get('logout', 'HomeController#getLogout');
Route::post('login', 'HomeController#postLogin');
});
Route::get('/', 'HomeController#getIndex');
Another way to improove you code, is think more restful. This Way you can handles methods like create, delete, index, update in one line of code like so:
Route::resource('products', 'ProductsController');
Take a look at: http://laravel.com/docs/controllers#resource-controllers

Related

Slim Authentication middleware for all routes except someone

I would like to have a Slim middleware to check authentication on all requests but some specific ones (for example login page).
I prepared the first AuthenticationMiddleware middleware to check all pages:
$app->add(new \App\Middleware\AuthenticationMiddleware($container));
Then I create another one AnonymousMiddleware that it is supposed to add a variable to set the exception to authentication checks:
$app->group('',function() use ($app){
$app->get('/','LogicController:index');
})->add(new AnonymousMiddleware($container));
The problem is that routes middleware (AnonymousMiddleware) is applied AFTER the general middleware (AuthenticationMiddleware);
I tried to use determineRouteBeforeAppMiddleware but it doesn't change the result.
I know I would set a route middleware for all authenticated routes but sounds a bit dangerous if I forget it, so, I would prefer to set which router are not under authentication then keep the check all other routes.
you need to chose different approach
you need to wrap all routes which should be "protected via Auth middleware" and exclude = not wrap routes which should not be handled by this middleware
you can add a group where all your routes will live and only login (and logout) route will be outside of this group ;)
something like
$app->group("/api/v1", function() {
// all your protected routes definitions here
})
->add(AuthenticationMiddleware::class)); // wrap by middleware
$app->post('/login', function(){});
$app->add(new MiddlewareForAllRoutes()); // middlewares for all routes

Laravel 5 redirect to path with parameters (not route name)

I've been reading everywhere but couldn't find a way to redirect and include parameters in the redirection.
This method is for flash messages only so I can't use this.
return redirect('user/login')->with('message', 'Login Failed');
This method is only for routes with aliases my routes.php doesn't currently use an alias.
return redirect()->route('profile', [1]);
Question 1
Is there a way to use the path without defining the route aliases?
return redirect('schools/edit', compact($id));
When I use this approach I get this error
InvalidArgumentException with message 'The HTTP status code "0" is not valid.'
I have this under my routes:
Route::get('schools/edit/{id}', 'SchoolController#edit');
Edit
Based on the documentation the 2nd parameter is used for http status code which is why I'm getting the error above. I thought it worked like the URL facade wherein URL::to('schools/edit', [$school->id]) works fine.
Question 2
What is the best way to approach this (without using route aliases)? Should I redirect to Controller action instead? Personally I don't like this approach seems too long for me.
I also don't like using aliases because I've already used paths in my entire application and I'm concerned it might affect the existing paths if I add an alias? No?
redirect("schools/edit/$id");
or (if you prefer)
redirect("schools/edit/{$id}");
Just build the path needed.
'Naming' routes isn't going to change any URI's. It will allow you to internally reference a route via its name as opposed to having to use paths everywhere.
Did you watch the class Illuminate\Routing\Redirector?
You can use:
public function route($route, $parameters = [], $status = 302, $headers = [])
It depends on the route you created. If you create in your app\Http\Routes.php like this:
get('schools/edit/{id}', 'SchoolController#edit');
then you can create the route by:
redirect()->action('SchoolController#edit', compact('id'));
If you want to use the route() method you need to name your route:
get('schools/edit/{id}', ['as' => 'schools.edit', 'uses' => 'SchoolController#edit']);
// based on CRUD it would be:
get('schools/{id}/edit', ['as' => 'schools.edit', 'uses' => 'SchoolController#edit']);
This is pretty basic.
PS. If your schools controller is a resource (CRUD) based you can create a resource() and it will create the basic routes:
Route::resource('schools', 'SchoolController');
// or
$router->resource('schools', 'SchoolController');
PS. Don't forget to watch in artisan the routes you created

Laravel controller define with mask

I have PagesController defined in my routes file:
Route::controller('/', 'PagesController');
But i use some more routes like:
Route::get('/admin', function()
{
....some code here
});
My second route doesn't work, because all other routes try to find functions in PagesController. I can change my controller to:
Route::controller('pages', 'PagesController');
But then in my home page, all links will be like www.test.com/pages/..., but i don't need that 'pages' in there. How to define my controller with mask or something like that?
Laravel allows you to easily define a single route to handle every action in a controller using simple, REST naming conventions. First, define the route using the Route::controller method:
Route::controller('pages', 'PagesController')
This is a single route to define all actions in a controller using REST naming conventions therefore you get the /pages.
For the root of your app you need to specify the method that you want to call within your PagesController.
Example:
Route::get('/', array('as' => 'home', 'uses' => 'PagesController#getIndex'));
Place this line at the top of your routes in the routes file.
Change the order of your route definition to this:
Route::get('/admin', function()
{
....some code here
});
Route::controller('/', 'PagesController');
It will now look for /admin first, and if it cant find it, it when they go to your other routes...
Try changing Route::controller({same content as the question}) to Route::resource({same content as the question})

Routing in laravel framework

I using the laravel framework of php for development.I done these following
steps
I define Route::resource('users', 'UsersController'); in route file and then define Route::get('user/pingme', 'UserController#pingme');
When i make a get call to pingme function, it was not working .I was getting the response code is 200 but code inside that pingme function was not working and i do not know why.
then i changed it to Route::post('user/pingme', 'UserController#pingme'); it was working fine as needed.
then what i did is, removed Route::resource('users', 'UsersController'); and make again get route to ping me function and make get call and it starts working fine .
so this is any bug in framework(rare thing) or i am missing something(probably yes)? Help me out....
Route file works as follows:-
if you have wrote a mapping for controller only, then it needs to come at the bottom of all other route mapping otherwise your program controller will pick route from user controller only and will redirect to UserController.
so the right order of all routes is:-
Route::get('user/pingme', 'UserController#pingme');
Route::post('user/logout', 'UserController#logout')->before('auth');
Route::resource('user', 'UserController');
OR
Route::post('user/logout', 'UserController#logout')->before('auth');
Route::get('user/pingme', 'UserController#pingme');
Route::resource('user', 'UserController');
In your route file, the order of the routes needs to be as follows:
Route::get('user/pingme', 'UserController#pingme');
Route::post('user/logout', 'UserController#logout')->before('auth');
Route::resource('user', 'UserController');
If Route::resource('user', 'UserController') comes before the other routes, the GET request to user/pingme will be handled by show method inside of UserController, because it is how Resourceful Controllers work. So, the Route::resource for user needs to come after all other routes with user/ prefix.

Laravel4 route pattern error

I´m using laravel 4 for a cms project, and i´m having some problems with my routes...
These are my current routes
Route::get('/', 'IndexController#showNews');
Route::get('/logout', 'UserController#logout');
Route::resource('/login', 'UserController');
Route::resource('/user', 'UserController#index');
Route::resource('/user/{route}', 'UserController');
// Routes that shows us the pages...
Route::get('/{page}', 'IndexController#showPage');
Route::get('/{page}/{id}', 'IndexController#showPage');
To my user routes i have a custom router that routes the user information around, not really a problem. But all of that works great, but when i try to navigate to "/test" Wich would link to a test page, it gives me this error.
Route pattern "/user/{route}/{{route}}" cannot reference variable name "route" more than once.
It comes up to router logic, and i´m fairly new to laravel. Is there a way for me to work around this problem? It´s a collision between the user/route and the /route wildcards.
Route::resource('/user', 'UserController#index');
Route::resource('/user/{route}', 'UserController');
The problem is that you are using Route::resource to declare the routes, while by using Route::resource you are actually declaring a RESTful controller with a table of actions to be handled by Laravel automatically. You are using it incorrectly.
See the docs to see which routes are handled in the background (and hence the source of the conflict):
Take a look at the table called Actions Handled By Resource Controller
For any route handler that is not within the table you will have to declare separate routes. Something like:
Route::get('foo/filter/{filterName}/{filterValue}',
array('as'=>'filteredroute','uses'=>'FooController#filter'))
As a summary, Route::resource enables you quick CRUD RESTful access.

Categories