So basically, I want to create my own Route::custom function.
This is because I've been using the same groups and middleware for several routes throughout the site (I'm also using modules with subdomains, so we're talking about saving 5-6 lines of code per route)
All I want is for Route::custom to just call two or three other Route functions. For example:
Route::Module('forum') to be replaced with
Route::group(['middleware' => ['web','auth'], 'domain' => 'forum.' . env('SITE_DOMAIN', 'example.com')], function () {
Route::group(['middleware' => 'permission:access.forum'], function () {
Route::get('/', function () {
return view('forum::forum.index');
})->name("forum.index");
});
});
You can extends laravel default facade then add static method as you want.
Notice: You must replace route facade config in config/app.php to your custom facade class.
Example here
I do not understand properly question 1. But for question 2, try this:
Go to app/Providers/RouteServiceProvider.php. Look for the function mapWebRoutes(). The line
require base_path('routes/web.php');
Duplicate it and change so you now have :
require base_path('routes/web.php');
require base_path('app/User/route.user.php');
require base_path('app/Whatever/route.whatever.php');
I guess this will resolve for your problem
Related
I started creating a REST API using the lumen framework and wanted to set up a particular behaviour for my GET /user route. Behaviour is the following:
If the request come from an authenticated user (using auth middleware), the method getAllFields from UserController is called and return all the data from the user
If it's not the case, the method get from UserController is called and return some of the data from the user
It seems logic to me to just write it like that in my web.php using a simple middleware:
<?php
$router->group(['middleware' => 'auth'], function () use ($router) {
$router->get('/user/{id}', [
'uses' => 'UserController#getAllFields'
]);
});
$router->get('/user/{id}', [
'uses' => 'UserController#get'
]);
But for some reason, even if the middleware is correct, I always get the response of the second route declaration (that call get()). I precise that if I remove the second route declaration, the one in the middleware work as expected.
Have someone an idea how I can achieve something similar that work?
Router will check if your request matches to any declared route. Middleware will run AFTER that match, so You cannot just return to router and try to find another match.
To fallow Laravel and Routes pattern - You should have single route that will point to method inside controller. Then inside that You can check if user is logged or not and execute getAllFields() from that controller. It will be not much to rewrite since You are currently using UserController in both routes anyway.
web.php
$router->get('/user/{id}', 'UserController#get');
UserController.php
public function get()
{
return auth()->check() ? YourMethodForLogged() : YourMethodForNotLogged();
}
Or if there is not much logic You can keep this in single method.
Also it is good idea to fallow Laravels REST standards (so use show instead of get, "users" instead of "user" etc - read more https://laravel.com/docs/7.x/controllers)
web.php
$router->get('/users/{user}', 'UserController#show');
UserController.php
public function show(User $user)
{
if (auth()->check()) {
//
} else {
//
}
}
To summary - for your needs use Auth inside controller instead of middleware.
To check if user is logged You can use Facade Auth::check() or helper auth()->check(), or opposite Auth::guest() or auth()->guest().
If you are actually using Lumen instead of full Laravel then there is not auth helper by default (You can make own or use package like lumen-helpers) or just keep it simple and use just Facades instead (if You have then enabled in Lumen).
Read more https://laravel.com/docs/7.x/authentication and https://lumen.laravel.com/docs/7.x/authentication
This pattern is against the idea of Laravel's routing. Each route should be defined once.
You can define your route without auth middleware enabled and then define your logic in the controller.
The routes/web.php have common application routes, Like showing the views, Getting the data from the form to a controller method.
The routes/api.php will have routes for getting records of the tables/entities in JSON. Updating, Deleting etc via api routes ?
Question 1 : How will i use my routes/api.php routes to get, delete, Update data/Records ?
Question 2 : Android app will be able to use my api ? If yes, How ?
Question 3 : The API should have a controller ApiController ?
Let the kid know the stuff !
Thanks
1:
Put this into your RouteServiceProvider file:
$router->group(['namespace' => $this->webNamespace], function ($router) {
require app_path('routes/web.php');
});
$router->group(['namespace' => $this->apiNamespace], function ($router) {
require app_path('routes/api.php');
});
1.1 in routes/web.php file (alternative):
require_once "../../routes/api.php";
2:
yes. use your routes as you would use them in any other frontend application. For example: localhost/api/myAndroidRoute
3:
doesn't really matter. you can use one controller for all the routes, or one controller for each route. Whichever option you like. If you have a lot of code, separate it into different controllers for better readibility.
For example:
Route::get('api/sampledata', 'ApiController#getSampleData'); // controller#function
Route::get('api/otherdata', 'SomeOtherController#getOtherData');
or
Route::get('api/sampledata', 'AllmightyController#getSampleData');
Route::get('web/otherdata', 'AllmightyController#getOtherData');
I am building a RESTful API using Laravel 5.1.
The default route would be api. The user is allowed to create a url service using as many as parameters as she wants let's say .../api/p1/p2/.../pn.
How do I make a single route to point to a single Controller, so the service will be handled in a single controller?
Note : At first the application just needs to know whether the service exists or not by comparing the url with stored service in the database. As for the service itself, it can be queried into the database later.
I read that we can use * in Laravel 4, how about Laravel 5.1 ?
I have tried :
Route::resource('/api/*', 'APIServiceController'); but it does not work for unlimited parameters
or is it possible to do it like this
Route::group(['prefix' => 'api'], function () {
//what should I put in the closure, how can I redirect it to a single controller
});
Write your route as below:-
Route::group(['prefix' => 'api'], function () {
// this route will basically catch everything that starts with api/routeName
Route::get('routeName/{params?}', function($params= null){
return $params;
})->where('params', '(.*)');
});
Redirect to controller,
Route::group(['prefix' => 'api'], function () {
Route::get('routeName/{params?}', 'YourController#action')->where('params', '(.*)');
});
If you want to make routeName dynamic then just write it in curly bracket as below:-
Route::get('{routeName}/{params?}', 'YourController#action')->where('params', '(.*)');
Hope it will help you :-)
You can try this trick
Route::get('{pageLink}/{otherParams?}', 'IndexController#get')->where('otherParams', '(.*)');
You should put it on the end of routes.php file as it is like a 'catch all' route.
class IndexController extends BaseController {
public function get($pageLink, $otherParams = null)
{
if($otherParams)
{
$otherParams = explode('/', $otherParams);
}
}
}
I have this blog resource which has the usual CRUD methods.(index, create, store, show, edit, update, destroy).
I have the following route in my routes.php:
Route::resource('blog', 'PostsController');
but I want to restrict all but index and show.
so I have
Route::get('blog', 'PostsController#index');
Route::group(array('before' => 'auth'), function()
{
Route::resource('blog', 'PostsController');
});
which is fine for index but I don't know how to route the show method ? Or is there another way? Instead of routing the resource should I route every URI individually and put the ones I want restricted in my restricted access route?
Cheers
Laravel has a feature that lets you specify filters in the controllers' __construct method using $this->beforeFilter. This function takes a second argument that lets your provide exceptions (or enable the filter only for certain methods). Try using your original routes file and set up your controller like this:
class PostsController extends BaseController {
function __construct() {
// ...
$this->beforeFilter('auth', array('except' => array('index', 'show')));
// ...
}
// ...
See Controller Filters in the Laravel documentation. It's not entirely well-documented, but you can also start a deeper journey into the guts of Laravel from here.
In Laravel 5 you use middleware function instead like this:
$this->middleware('auth', array('except' => array('index', 'show')));
How can I create admin specific routes in Laravel 4 (Restfull Controllers):
/admin/users (get - /admin/users/index)
/admin/users/create (get)
/admin/users/store (post)
I want to know:
What Files and where I need create theam
How I need create the route
In Laravel 4 you can now use prefix:
Route::group(['prefix' => 'admin'], function() {
Route::get('/', 'AdminController#home');
Route::get('posts', 'AdminController#showPosts');
Route::get('another', function() {
return 'Another routing';
});
Route::get('foo', function() {
return Response::make('BARRRRR', 200);
});
Route::get('bazz', function() {
return View::make('bazztemplate');
});
});
For your subfolders, as I answer here "route-to-controller-in-subfolder-not-working-in-laravel-4", seems to have no "friendly" solution in this laravel 4 beta.
#Aran, if you make it working fine, please add an code sample of your controller, route, and composer.json files :
Route::resource('admin/users', 'admin.Users');
or
Route::resource('admin', 'admin.Users');
thanks
Really useful tool that you can use is the artisan CLI.
Using this you'll be able to generate the needed function file with all the required routes for it to become RESTful.
php artisan controller:make users
Would generate the function file for you. Then in your routes.php file you can simply add
Route::resource('users', 'Users');
This'll setup all the necessary routes.
For more information on this you should read the documentation at.
http://four.laravel.com/docs/routing#resource-controllers
http://four.laravel.com/docs/artisan
Edit:
To make this admin specific, simple alter the code like follows and move the controller to a admin folder inside the controllers folder.
Route::resource('admin/users', 'admin.Users');
The first paramater is the route, the second is the controller filename/folder.
In Laravel if you placed a controller inside a folder, to specific it in a route or URL you'd use the a dot for folders.
You can then expand on this and add Authentication using Route Filters and specifically the code found "Pattern Based Filters" found on the page below.
http://four.laravel.com/docs/routing#route-filters
Laravel 4 - Add Admin Controller Easily
This was driving me insane for ages, but i worked it out.
routes.php
Route::resource('admin', 'Admin_HomeController#showIndex');
/controllers/Admin/HomeController.php
Notice the folder name Admin must be captital 'A'
<?php
class Admin_HomeController extends Controller {
public function showIndex() {
return 'Yes it works!';
}
}
Alternatively you can use the group method
Route::group(array('prefix' => 'admin'), function() {
Route::get('/', 'Admin_HomeController#showIndex');
});
Thanks
Daniel