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');
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.
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
I cloned this todstoychev/Laravel5Starter from Github and installed it.
After creating this StaticPagesController controller and updating my routes.php file. The controller does not seem to work. For some reason i keep getting the following error.
ReflectionException in ControllerInspector.php line 32:
Class App\Http\Controllers\StaticPagesController#faq does not exist
My routes.php file
<?php
// Admin routes
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () {
Route::controller('permissions', 'AdminPermissionsController');
Route::controller('settings', 'AdminSettingsController');
Route::controller('roles', 'AdminRolesController');
Route::controller('users', 'AdminUsersController');
Route::controller('/', 'AdminController');
});
// Public and user routes
Route::controller('contacts', 'ContactsController');
Route::controller('users', 'UsersController');
Route::controller('/', 'IndexController');
Route::controller('faq', 'StaticPagesController#faq');
My StaticPagesController.php file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StaticPagesController extends Controller
{
public function faq(){
return 'this is faq page';
}
}
I have tried composer update, php artisan acl:update, composer dumpautoload to no avail.
Please help me. Thanks
With this line:
Route::controller('faq', 'StaticPagesController#faq');
You are telling Laravel that the controller for faq shoule be StaticPagesController#faq. The Route::controller method sets an entire controller for a route, it does not specify a method to be used on that route, Laravel handles this internally. Take a look at your error to prove my point:
Class App\Http\Controllers\StaticPagesController#faq does not exist
It is looking for class StaticPagesController#faq not StaticPagesController as you are intending.
Unless you are building an API using REST, you should not use the controller method and instead specify your routes explicitly, i.e.
Route::get('faq', 'StaticPagesController#faq');
This will use the faq method on your controller when the user makes a GET request to the URI faq. If you insist on using the controller method, then remove the #faq from the second argument and you will be good, although I'm pretty sure Laravel expects the methods index, show, create, etc to be in your controller. I suggest taking a look at the Laravel 5 Fundamentals video course to help you get a better understanding.
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
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