Routing api to a controller in Laravel - php

I want to create a custom public API; and answer all api requests under ApiController with a routing like this:
Route::resource("/api","ApiController");
I tried to add this under routes/web or routes/api; but no chance. I get "Sorry..page not found".
Other routing options under routes/web work fine; I only have a problem when it comes to /api.
Should I proceed with a route like /custom_public_api or is there anything I can do about this?

If you put this in your api.php
Route::resource("/users","UserController");
Than the routes will be automatically prefixed with /api.
So the routes will look like this:
/api/users
/api/users/{user}
...
So in your case it is not working because you have this type of routes:
/api/api
/api/api/{api}
/api/api/{api}/edit
...
So you're having api twice. So you just have to suppose that the api prefix, is automatically added from routes/api.php.
For more information about your routes, you can run php artisan route:list and you can check how do your routes look like.

For api resources you have to use
Route::apiResource('photos', 'PhotoController');
as says in the documantation here (just scroll a little until you get to API Resource Routes)

Related

Laravel getting 404 error when creating new route

it appears that when I created a new route, I receive the 404 error when trying to access the url, which is funny,. because all of my other routes are working just fine.
My web.php looks like so:
Auth::routes();
Route::post('follow/{user}', 'FollowsController#store');
Route::get('/acasa', 'HomeController#index')->name('acasa');
Route::get('/{user}', 'ProfilesController#index')->name('profil');
Route::get('/profil/{user}/edit', 'ProfilesController#edit')->name('editareprofil');
Route::patch('/profil/{user}', 'ProfilesController#update')->name('updateprofil');
Route::get('/alerte', 'PaginaAlerte#index')->name('alerte');
Route::get('/alerte/url/{user}', 'UrlsController#index')->name('editurl');
Route::post('/alerte/url/{user}', 'UrlsController#store')->name('updateurl');
Route::get('/alerte/url/{del_id}/delete','UrlsController#destroy')->name('deleteurl');
The one that is NOT working when I am visiting http://127.0.0.1:8000/alerte is:
Route::get('/alerte', 'PaginaAlerte#index')->name('alerte');
The controller looks like so:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class PaginaAlerte extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function index(User $user)
{
return view('alerte');
}
}
I am banging my head around as I cannot see which is the problem. It is not a live website yet, I am just developing on my Windows 10 pc using WAMP.
Moved my comment to a little bit explained answer.
So, in your route collection, you have two conflicting routes
Route::get('/{user}', 'ProfilesController#index')->name('profil');
and
Route::get('/alerte', 'PaginaAlerte#index')->name('alerte');
Imagine that Laravel is reading all routings from top to bottom and it stops to reading next one after the first match.
In your case, Laravel is thinking that alerte is a username and going to the ProfilesController#index controller. Then it tries to find a user with alerte username and returning 404 because for now, you don't have a user with this username.
So to fix 404 error and handle /alerte route, you just need to move the corresponding route before /{username} one.
But here is the dilemma that you got now. What if you will have a user with alerte username? In this case, the user can't see his profile page because now alerte is handling by another route.
And I'm suggesting to use a bit more friendly URL structure for your project. Like /user/{username} to handle some actions with users and still use /alerte to handle alert routes.
The following route catches the url /alerte as well
Route::get('/{user}', 'ProfilesController#index')->name('profil');
Since this one is specified before
Route::get('/alerte', 'PaginaAlerte#index')->name('alerte');
The /alerte will go the the ProfilesController instead.
To fix this change the order of the url definitions or change either of the urls to have nesting e.g. /alerte/home or /user/{user}
Well.
Maybe this is too late, but I have all week dealing with this problem.
I made my own custom.php file and add it in the routes path of my Laravel project, and none of the routes were working at all.
This is how I solved it:
You must remember to edit the RouteServiceProvider.php file located in app\Providers path. In the map() function, you must add your .php file. That should work fine!
To avoid unexpected behaviors, map your custom routes first. Some Laravel based systems can "stop" processing routes if no one of the expected routes rules were satisfied. I face that problem, and was driving me crazy!
I would wish suggest to you declare your URL without the "/", like your first "post" route, because sometimes, I have been got this kind of errors (404).
So, my first recomendation is change the declaration of the route. After that, you should test your middleware, try without the construct, and try again.
Good luck!

Laravel Forwarding Route To Another Route File

I'm building enterprise modular Laravel web application but I'm having a small problem.
I would like to have it so that if someone goes to the /api/*/ route (/api/ is a route group) that it will go to an InputController. the first variable next to /api/ will be the module name that the api is requesting info from. So lets say for example: /api/phonefinder/find
In this case, when someone hit's this route, it will go to InputController, verifiy if the module 'phonefinder' exists, then sends anything after the /api/phonefinder to the correct routes file in that module's folder (In this case the '/find' Route..)
So:
/api/phonefinder/find - Go to input controller and verify if phonefinder module exists (Always go to InputController even if its another module instead of phonefinder)
/find - Then call the /find route inside folder Modules/phonefinder/routes.php
Any idea's on how to achieve this?
Middlewares are designed for this purpose. You can create a middleware by typing
php artisan make:middleware MiddlewareName
It will create a middleware named 'MiddlewareName' under namespace App\Http\Middleware; path.
In this middleware, write your controls in the handle function. It should return $next($request); Dont change this part.
In your Http\Kernel.php file, go to $routeMiddleware variable and add this line:
'middleware_name' => \App\Http\Middleware\MiddlewareName::class,
And finally, go to your web.php file and set the middleware. An example can be given as:
Route::middleware(['middleware_name'])->group(function () {
Route::prefix('api')->group(function () {
Route::get('/phonefinder', 'SomeController#someMethod');
});
});
Whenever you call api/phonefinder endpoint, it will go to the Middleware first.
What you are looking for is HMVC, where you can send internal route requests, but Laravel doesn't support it.
If you want to have one access point for your modular application then you should declare it like this (for example):
Route::any('api/{module}/{action}', 'InputController#moduleAction');
Then in your moduleAction($module, $action) you can process it accordingly, initialize needed module and call it's action with all attached data. Implement your own Module class the way you need and work from there.
Laravel doesn't support HMVC, you can't have one general route using other internal routes. And if those routes (/find in your case) are not internal and can be publicly accessed then also having one general route makes no sense.

Laravel Routing Parameter Contraint

Been working on a neat little project. I'm using Laravel 5.5, and I'm building routes to handle the various requests. I've got a route that accepts a slug to locate a particular guild via route model binding. Works great! Beautifully, actually. Then, I defined a "static" route that doesn't use a parameter to show the form for creating a new guild. Here's the routes...
Route::get('/guilds', 'GuildController#index')->name('guilds');
Route::get('/guild/{guild}', 'GuildController#show')->name('guild');
Route::get('/guild/create', 'GuildController#create')->name('create_guild');
Route::get('/guild/{guild}/edit', 'GuildController#edit')->name('edit_guild');
Route::post('/guild/create', 'GuildController#store')->name('store_guild');
But when I attempt to navigate to '/guild/create', I get a 404 because a guild with the slug "create" doesn't exist. How can I work around this particular issue?
Try put specific routes first:
Route::get('/guilds', 'GuildController#index')->name('guilds');
Route::get('/guild/create', 'GuildController#create')->name('create_guild');
Route::post('/guild/create', 'GuildController#store')->name('store_guild');
Route::get('/guild/{guild}', 'GuildController#show')->name('guild');
Route::get('/guild/{guild}/edit', 'GuildController#edit')->name('edit_guil');

laravel routes, how to group similar in one file

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.

Laravel route to controller not working

I'm trying to add a new controller to an existing laravel project. The application already has some pages at /users and I am trying to add a RESTful API which works separately to this. I would like the API to be available at api/users.
I have created the controller using PHP artisan:
php artisan controller:make ApiUsersController
I have added the following to my routes:
Route::controller('api/users', 'ApiUsersController');
However when I hit the URL I just receive the site's 'Page could not be found' message.
Is there something I have missed?
It looks like the issue you're having is that you've used Route::controller rather than Route::resource.
Route::resource maps routes to the seven RESTful methods that the controller generator creates by default. Route::controller maps them to methods that you add yourself that have the HTTP method as part of their name, in your case if you had a method called getIndex it would be called on a GET request to /api/users/index or if you had one called postStore it would be called on a POST request to /api/users/store.
In order to add the API prefix to the route you could use the following:
Route::group(['prefix' => 'api'], function() {
Route::resource('users', 'ControllerName');
});
You could also add any other controllers in the API within the same callback.

Categories