I am new to laravel 4 framework but was previously working on CI and CakePHP, i have some problems with routes in it (i may sound nerd, so bear with me.)
-> If i have 3 controller userController,adminController,editorController and many methods inside them, do i need to define routes for every methods inside it (ofcourse i am not using ResourceFull controller for them). Can't i have something by which the methods can be accessed by using the controllername followed by method name like we do in other frameWork.
E.g usersController have manageUser method, i wnt to access it like
http://localhost/project/users/manageUser
-> What is use of defining a route using Route::controller('users', 'UserController'); or restfull controller?
Thanks in advance :)
If you write
Route::controller('users', 'UserController')
runs the default function (index of all the objects), but you can write:
Route::get('/users', 'userController#function');
or
Route::post('/users', 'userController#function');
this route shows to Laravel what controller and function can call when you write this route, the diference is if you pass the parameters with get or post mode.
Hope I help you
Related
i have this route defined in my routes file ::
Route::get('user/dashboard', ['as'=>'dashboard', 'uses'=>'AdminController#index']);
and i am trying to read the name of the route, in this case 'dashboard', in all my views, already i know how to pass that using the view::share() method.
I have checked everywhere online, and looking through the laravel API, i have seen several methods two of which are,
//1. Route::currentRouteName();
//2. Route::getName();
but none of them seems to be working, please what am i doing wrong and what is the best way to get the name string...
regards.
The Request class provides many methods for examining the HTTP request for your application and extends the Symfony\Component\HttpFoundation\Request class
Write Request::path() to get current URI.
Check this Documentation
I'm working with laravel(5.2), and there are a lot routes in my route file.
in fresh install I noticed that it was loading auth routes something like this.
Route::auth();
nothing else was there in routes.php file related to auth routes.
in my file, I've like this one
Route::get('color/event', 'ColorController#index');
Route::post('color/event', 'ColorController#post_message);
...
...
and many others, So I want to load all in laravel way, like Route::color(); and it should load all color related routes
Thanks for you time
you can try this
Route::resource('admin/settings','Admin\SettingsController');
and try this command
$ php artisan routes
Using Route::get(), Route::post() and similar functions is doing it the Laravel way - see the docs here https://laravel.com/docs/5.2/routing#basic-routing
Route::auth() is just a helper function introduced in Laravel 5.2 to keep all auth definitions together.
so, anyone if s/he is looking for same answer, I figured that out.
if you want something like Route::auth(); OR Route::color();//in my case or whatever you want to call it, you need to add custom function in your Router.php file. So solution will look like
//inside Router.php file
public function whatever(){
$this->get('app/', 'AppController#index');
$this->post('app/new', 'AppController#create');
}
and in your route.php file, you can do this.
Route::whatever();
But this is really dirty way to do that
so instead you can extend the base Router and register your router in bootstrap/app.php
$app->singleton('router', 'App\Your\Router');
so I community forces to use second approach.
for more details, have a look here.
Extending Router(laravel.io forum)
Extending default Laravel 5 Router
How to extend Router or Replace Customer Router class on Laravel5?
hope someone will find this useful
Thanks.
I'm trying to set up a routing prefix in cakephp 3 so any URLs starting with /json/ get the prefix key set and I can change the layout accordingly in the app controller. Other than that, they should use the usual controller and action. I have added the following to routes.php
$routes->prefix('json', function($routes) {
$routes->connect(
'/:controller/:action/*',
[],
['routeClass' => 'InflectedRoute']
);
});
I want to direct all requests with json as first url segment to controller specified in second url segment. e.g. /json/users/add_account_type/ goes to users controller. However when accessing this URL I get the message:
Error: Create the class UsersController below in file:
src/Controller/Json/UsersController.php
whereas I want it to be using
src/Controller/UsersController.php
I think this should be possible but I can't quite see what I'm doing wrong when consulting the book. Have partly based my code on: CakePHP3.x controller name in url when using prefix routing
Thanks a lot in advance
That's simply how prefix routing now works in 3.x, as explained in the docs, prefixes are being mapped to subnamespaces, and thus to separate controllers in subfolders.
http://book.cakephp.org/3.0/en/development/routing.html#prefix-routing
If you'd wanted to change that behavior (I don't really see why), one way would be to implement a custom ControllerFactory dispatcher filter.
http://book.cakephp.org/3.0/en/development/dispatch-filters.html
On a side note, the RequestHandler component supports layout/template switching out of the box, so maybe you should give that a try.
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html
http://book.cakephp.org/3.0/en/views/json-and-xml-views.html
Prefix routing is a way of namespacing parts of your routes to a dedicated controller. It seem that what you want is a scope and not a prefix, for what you describe:
Router::scope('/json', function($routes) {
$routes->fallbacks('InfledtedRoute')
});
As I am new to the laravel 4 after spending some few months in Codeigniter, I went through the lots of tutorials about laravel and one thing I want to be clear is what is the actual difference between Routes and Controller in laravel, because we can create and generate view in both controller and routes too. Will anyone explain me in brief when to use routes and Controller in laravel? Because in other Framework we need routes to specify some particular URL's within the apps and Controller were used to do some real tasks but in laravel I didnt get the main concept of Routes except the routing mechanism?
In Laravel, you can totally skip controllers and do the task of performing business logic and generating the view in the routes.
E.g I have a link b2.com/getUsers so in routes.php I can write:
Route::get('/getUsers',function()
{
$users=User::all(); //select * from users
return View::make('allUsers')->with('users',$users);
}
So, here to serve the request b2.com/getUsers, we didn't use controller at all and you can very well do this for handling all requests in your application, both get and post.
But then, if your application is large and have 500+ url's with complex business logic then imagine putting everything in one routes.php. It will totally make it criminally messy and whole purpose of architecture will be defeated. Hence what we usually do is, reserve routes.php for routing only and write all business logic (along with generation of views inside controllers)
So the same example can be solved as:
To handle link: b2.com/getUsers, in routes.php
Route::get('/getUsers', array('before' => 'auth', 'uses' => 'MyController#getUsers'));
MyController has the method getUsers defined like this:
public function getUsers()
{
$users=User::all(); //select * from users
return View::make('allUsers')->with('users',$users);
}
I usually create a controller for related activities e.g for login/signup/logout. I create AuthController and all the links related to those activities are routed to AuthController through routes.php.
The fact that you can get views or do a lot of things in Routes::any() is against MVC and separation of logic.
In Route::get("admin", function(){}), you indeed have a fast access to your route callback, which otherwise in a standard fashion must just be bound to controller. But Laravel allows you to do your job there in a closure (function(){}), instead of binding it to a controller. Anyway, it lets you, but you'd better avoid it. In Route::get() you only should go with your 'routing' and nothing more.
There is no reason for you to use callbacks in Route unless for testing or some trivial requests. So, better to avoid this:
Route::get("admin", function(){
return View::make("admin_index");
});
And rather go with this:
Route::controller("admin", "AdminController");
And in your AdminController.php :
// I mean create a file named AdminController.php in controllers directory under app.
class AdminController extends Controller
{
function getIndex()
{
return View::make("admin_index");
}
}
Read more about Route::controller and restful controllers.
Some Notes:
Having the ability to add closures in your Routes allows you to make
complex decisions on Routes and have a powerful routing system.
These callbacks let you add conditions to your route.
Having Controller separated from you Routes makes you application
more extensible, less confusing and makes other coders more
comfortable in future.
It allows you to focus better on your problem and finding solution,
this physical separation is very important. Having View::make()
inside your Route stirs all problems into each other and makes up a
confusion for the coder.
Let's see what we have in both cases:
In CodeIgniter, a route is just pointing your request to a specific method of your controller:
$route['blog/joe'] = "blogs/users/34";
Here when you visit application.com/blog/joe, you will invoke the controller BlogsController, call the method users() and pass 34 as the first parameter. Nothing else. As they put it, a route in CI is just a one-to-one relationship between a URL string and its corresponding controller class/method.
Now, in Laravel, you have a lot of possibilities:
You can directly return a simple response
You can return a view
You can point the request to a specific controller and a method
You can write some logic in a closure and then decide what you want to do
You can add some additional functionality to them, like attaching filters, checking parameters upon a regex, give them separate names, etc., but this is the main functionality.
What's the reason for being able to do so much stuff? It gives you the power to use them in any way you need. Examples:
Need a small website, rendering static HTML? Use them like this:
Route::get('/', function()
{
return View::make('greeting');
});
Need a bigger application using the traditional MVC pattern? Use like this:
Route::get('user/{id}', 'UserController#showProfile');
Need a RESTful approach? No problem. This will generate routes for all the CRUD methods:
Route::resource('photo', 'PhotoController');
Need something quick and dirty to handle a specific Ajax request? Keep it simple:
Route::post('foo/bar', function()
{
return 'Hello World';
});
TL;DR: For very simple things without or with very little logic, use them instead of controllers. Otherwise, always stick to the MVC principles and route to your controllers, so that they're the ones who do the actual work.
Laravel routing functionality allows you to name a resource and name a controller to go with it. I am new to Laravel and would like to know if anyone knows how to extend the resources method in the route class provided.
Basically say I have: (which works fine)
/invoices
But say I want:
/invoices/status/unpaid
How is this achievable?
To see the basics of what I am doing check:
http://laravel.com/docs/controllers#resource-controllers
Resource controllers tie you into a specific URLs, such as:
GET|POST /invoices
GET|PUT /invoices/{$id}
GET /invoices/create
and so on as documented.
Since, by convention, GET /invoices is used to list all invoices, you may want to add some filtering on that:
/invoices?status=unpaid - which you can then use in code
<?php
class InvoiceController extends BaseController {
public function index()
{
$status = Input::get('status');
// Continue with logic, pagination, etc
}
}
If you don't want to use filtering via a query string, in your case, you may be able to do something like:
// routes.php
Route::group(array('prefix' => 'invoice'), function()
{
Route::get('status/unpaid', 'InvoiceController#filter');
});
Route::resource('invoice', 'InvoiceController');
That might work as the order routes are created matter. The first route that matches will be the one used to fulfill the request.