I am confused about routing in laravel - php

in routes.php,we write some route for the controller. such as:
Route::post('/account/create',array(
'as' =>'account-create',
'uses'=>'AccountController#postCreate'
));
I know that 'uses' is to search for the controller,then what 'as' is dealing with?

as is used to create a named-route in laravel.
As the doc says:
we can use them to refer to the route while generating URLs or redirects:
//generate URL
$url = URL::route('account-create');
//redirect to the route from another
$redirect = Redirect::route('account-create');
// with helpers
$url = route('account-create');
$redirect = redirect()->route('account-create');

as is for creating named routes and in fact it's very useful. In your application you can create urls or redirection using this named route URL::route('account-create'); and Redirect::route('account-create'); and it gives you huge bonus.
If you decide that you want to change your url, you just change it in your route and everything will be working without a problem because in other parts you used only route name.
So for example if you use named routes:
Route::post('/account/create',array(
'as' =>'account-create',
'uses'=>'AccountController#postCreate'
));
and in other parts URL::route('account-create'); and Redirect::route('account-create'); and now you decide you want to change url from /account/create to newaccount you need to change only in routes.php /account/create to newaccount and your whole application will work without a problem
On contrary, if you used urls in other part of your application, if you want to change this route url you would need to change urls in many parts of your application so you should use named routes because it can save you huge amount of time if you decide to change some urls in future.
For example if you don't use named-routes:
Route::post('/account/create',array(
'uses'=>'AccountController#postCreate'
));
and in other parts URL::to('/account/create'); and Redirect::to('/account/create'); and now you decide to change your url from /account/create to newaccount you will need to change it not only in routes.php file but in all files that use this url where you make any URL::to('/account/create'); or Redirect::to('/account/create');

Related

When to use: redirect('/') vs. redirect()->route('home') vs. redirect()->home()?

When I have this named route:
Route::get('/', 'IndexController#index')->name('home');
Then in any action method of any Controller; when I need to redirect to the named route home; any of these statements redirects properly to the intended route:
return redirect('/');
return redirect()->route('home');
return redirect()->home();
When to use each?
What are the differences?
Are there any benefits of using one over the others?
As the documentation mention :
When you call the redirect helper with no parameters, an instance of
Illuminate\Routing\Redirector is returned, allowing you to call any
method on the Redirector instance. For example, to generate a
RedirectResponse to a named route, you may use the route method
As you can see in the API methods(link below) there is a lot of methods that you can use and also there is one specific helper method home() it's just a shortcut for redirect()->route('home') as highlighted by #ceejayoz.
Now the we will talk about return redirect('/'); and return redirect()->route('home'); the two of them redirects properly to the intended route as you said BUT the second one is really useful if in the future.
Why ?
Because if you want to change the URL structure in the routes file all you would need to change is the route only for example :
Route::get('/', 'IndexController#index')->name('home');
Will be :
Route::get('/home_page', 'IndexController#index')->name('home');
and all the redirects would refer to that route and there is no other thing that you should change => all redirects will still work perfectly.
BUT
If you choose to use the first one (i mean return redirect('/');) then after the change in the route you will need to parse all your controllers to check if there is some redirects that uses then changed route and the change them :p
redirect()->home() is simply a shortcut for redirect()->route('home'). The source code can be seen here.
Named routes are generally better than raw URLs for maintainability purposes. The home route isn't all that likely to change location, but it is possible that you might host a Laravel app in a subfolder, or move the home page from / to /app to make room for a marketing landing page at the root.
redirect('/')
It redirects you to the base URL.
redirect()->route('home')
Redirects to the route named home.
See More about named routes here.
redirect()->home();
Alternative way to redirect to named route.Redirects to 'home' route as well. It does the same thing as above but with slightly different syntax.
I preferred named routes over raw URLs, because if you decide to change the URL later on, you have to make changes into your routes file only.
When you are passing a string it will redirect a user to the domain plus the string you pass.
http://localhost:3000 + string
It will also add / if you forget it, now if you name your routes like you did then you can call it by the name.
An advantage of using named routes is in case you want to change the URI you can do it without worrying about changing a bunch of ahref in your view, redirects in your controllers, etc.
home() is a method from Laravel's Redirector or redirect() so, I don't think you can just call a named route as a method.

Laravel named routing | Auto generating urls to best possible match

I am trying to name my routes so I can easily generate urls instead of using the url helper function in which I have to type myself.
I am doing this:
Route::get('logout', 'PageController#logout')->name('pc');
When I do php artisan route:list I don't get this named route, instead name column is empty.
What I want is that, whatever views I target through this controller. I want to generate their urls like this.
route('pc.logout') OR route('pc.some_other_action')
So even if I change the verb to access this controller from the URL address, I don't have to change my url generator. Is this even possible in Laravel? Please also tell how to do this for resource routes.
I am using Laravel 5.3.
Thanks.
EDIT: Next day 1/11/2017
What I am expecting is that like ASP.NET MVC routing, if I tell it to generate a url with given controller and actions, it will generate the possible route to it regardless of the verb or string used to name the route.
For example
If I make a url like this
route('users.index')
Outputs /users
but if I change the string name users to u, instead of giving me error that name 'users' doesn't exist it should auto generate a url output like this:
Output: /u
This is a part of ASP.NET MVC routing system, I am expecting to see this here as well.
You should write this This will solve your problem
Route::get('logout', array('as' =>'pc.logout' ,'uses' => 'PageController#logout'));
This might solve your problem
you can define the named route as this
Route::get('/logout',[
'uses'=>'web\PageController#logout',
'as'=>'pc'
]);
Try this:
<?php
Route::get('logout',[
'uses'=>'PageController#logout',
'as'=>'pc.logout'
]);
name('pc.logout') OR name('pc.some_other_action')
You can try this one.
It is much simpler way to use:
Route::get('logout', 'PageController#logout')->name('pc.logout');
Or like this:
Route::get('logout', 'PageController#logout')->name('pc.some_other_action');
can you explain further if this is wrong.

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 - why not relative URL's?

I have been learning Laravel recently and I have seemingly missed a key point: why should relative links be avoided?
For example, I have been suggested to use URL::to() which outputs the full path of the page passed as a parameter - but why do this when you could just insert a relative link anyway? E.g., putting URL::to('my/page') into a <href> will just insert http://www.mywebsite.com/my/page into the <href>; but on my website href='my/page' works exactly the same. On my website I have based all relative URL's from the index.php file found in the public directory.
Clearly, I'm missing a key point as to why full paths are used.
I've found that using route() on named routes to be a much better practice. If at one point you decide, for example, that your admin panel shouldn't point to example.com/admin, but example.com/dashboard, you will have to sift through your entire code to find all references to Url::to("/admin"). With named routes, you just have to change the reference in routes.php
Example:
Route::get('/dashboard', ['as' => 'admin', 'uses' => 'AdminController#index']);
Now every time you need to provide a link to your admin page, just do this:
Admin
Much better approach, in my opinion.
This is even available in your backend, say in AdminController.php
// do stuff
return redirect()->route('admin');
http://laravel.com/docs/5.1/routing#named-routes
Neither absolute nor relative links should be used - it's advisable to use named routes like so:
Route::get('my/page', ['as' => 'myPage', function () {
// return something
}]);
or
Route::get('my/page', 'FooController#showPage')->name('myPage');
Then, generate links to pages using URL::route() method (aliased as route() in L5), which is available in Blade as well as in your backend code.
That way, you can change the path to your routes at any time without having to worry about breaking links anywhere in your application.

Generating url relative to the base url in laravel 4

I'm new to Laravel & right now building one application on L-4 but got stuck at one place. Can't able to understand how to generate url relative to base url. In laravel-3 i know this can be done by
$url = URL::to('user/profile');
But, in L-4 how we can do this.. ?
To generate a relative URL, you can use URL::route or URL::action as they allow to pass a $absolute parameter which defaults to true. So to get a relative URL when using named routes for example, you can use the following:
URL::route('foobar', array(), false)
This will generate a URL like /foobar.
First you need to create a Named Route like
Say yo want to go to http://baseurl/user and runs the method 'showuser' define in controller 'allusers'
then your Route shold look like this:-
Route::get('user', array('as' => 'myuser', 'uses' => 'allusers#showuser'));
Now your URL to /user would be
$myuserurl = URL::to('/myuser');
echo $myuserurl; // would be http://baseurl/user
I hope this helps you. Pls refer http://laravel.com/docs/routing#named-routes

Categories