How to Set API routes in Laravel 8.0? - laravel

I was working in laravel 8.x, I have developed API to register, but when i test using postman also in browser the url [1]: http://127.0.0.1:8000/api/register always returns 404 not found message.
below is my api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'v1'], function () {
Route::post('/login', 'UsersController#login');
Route::post('/register', 'UsersController#register');
Route::get('/logout', 'UsersController#logout')->middleware('auth:api');
});
can you please help?

Since you already put a route group "v1", all your routes must have that prefix, so just api/register wont work because that route doesn't exist inside your api.php, so infront of your routes just use
http://127.0.0.1:8000/api/v1/register
http://127.0.0.1:8000/api/v1/login
http://127.0.0.1:8000/api/v1/logout

Your routes looking fine.
I think you are forgetting to add http://127.0.0.1:8000/api/**v1**/register so please try with it once.

Related

Laravel edit route for basic CRUD application giving 404

I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes

Laravel Route not defined for registercontroller

I'm new to Laravel and I inherited a project. I saw that there was a app/Http/Controller/Auth/RegisterController.php, but going to the websites /register gave me a 404 error. So I added this line to routes/web.php
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And now I can go to the url /register and sign up a new user without any issues.
I went into resources/views/auth/login.blade.php and added the line
Don't have an account? Sign up
But this gave me an error Route [register.create] not defined. View(.. path to login.blade.php
What did I do wrong?
Answer
The reason why you it's returning a 404 is because when you manually register the registration routes and you do it before the Auth::routes which registers one with the same key that overwrites yours. Hence why it's working if you move them after the Auth::routes.
What you could do is disable the register routes from the Auth facade:
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes(['register' => false]);
If you plan on using Laravel's default registration system, you simply have to remove your manually registered routes and create the respective views and you can access the route with route('register');.
You can also check the other available routes generated by the Auth facade with php artisan route:list.
Note
Also, you do not need to group them in the web middleware when adding routes in routes/web.php because they are automatically in the middleware by the RouteServiceProvider.
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
I solved the problem. I made a guess changed this:
Route::group(['middleware' => ['web']], function () {
... other code ...
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
Auth::routes();
... other code ...
});
To this
Route::group(['middleware' => ['web']], function () {
... other code ...
Auth::routes();
... other code ...
});
Route::get('/register', 'RegistrationController#create')->name('register.create');
Route::post('/register', 'RegistrationController#store');
And it worked. NOt sure if this is the right way to do it though

laravel Unable to prepare route ... for serialization. Uses Closure

When I clear caches in my Laravel 5.2 project, I see this error message:
[LogicException]
Unable to prepare route [panel] for serialization. Uses Closure.
I think that it's related with a route
Route::get('/article/{slug}', 'Front#slug');
associated with a particular method in my controller:
public function slug($slug) {
$article = Article::where('slug',$slug)->first();
$id = $article ->id_article ;
if ( ($article=== null) || (is_null($id)) ) return view('errors/Db');
else return view('detail')->with(array('article'=> $article, 'title'=>'My title - '.$article->title));
}`
In short, from a master view I pass $slug, that is a shortlink to the article, with $slug , which is unique in the database, I identify the record and then I pass it's contents to the detail view.
I didn't have any problem when I wrote the method, infact it worked like a charm, but after I cleaned caches, I get that error and the links in the master view don't show any shortcode.
Where am I doing wrong?
I think that it's related with a route
Route::get('/article/{slug}', 'Front#slug');
associated with a particular method in my controller:
No, thats not it. The error message is coming from the route:cache command, not sure why clearing the cache calls this automatically.
The problem is a route which uses a Closure instead of a controller, which looks something like this:
// Thats the Closure
// v
Route::get('/some/route', function() {
return 'Hello World';
});
Since Closures can not be serialized, you can not cache your routes when you have routes which use closures.
If none of your routes contain closures, but you are still getting this error, please check
routes/api.php
Laravel has a default auth api route in the above file.
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which can be commented or replaced with a call to controller method if required.
This is definitely a bug.Laravel offers predefined code in routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which is unabled to be processed by:
php artisan route:cache
This definitely should be fixed by Laravel team.(check the link),
simply if you want to fix it you should replace routes\api.php code with some thing like :
Route::middleware('auth:api')->get('/user', 'UserController#AuthRouteAPI');
and in UserController put this method:
public function AuthRouteAPI(Request $request){
return $request->user();
}
The Actual solution of this problem is changing first line in web.php
Just replace Welcome route with following route
Route::view('/', 'welcome');
If still getting same error than you probab
the solustion when we use routes like this:
Route::get('/', function () {
return view('welcome');
});
laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize
Check your routes/web.php and routes/api.php
Laravel comes with default route closure in routes/web.php:
Route::get('/', function () {
return view('welcome');
});
and routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
if you remove that then try again to clear route cache.
If you're coming to this problem because you've upgraded Laravel <5.8 project up to >=5.8, you've likely used the ./vendor/bin/carbon-upgrade method to upgrade the project as suggested by your terminal. In this case, you simply need to remove the following two blocks from the bottom of your composer.json file and composer install again:
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
],
If someone is still looking for an answer, for me the problem was in routes/web.php file. Example:
Route::get('/', function () {
return view('welcome');
});
It is also Route, so yeah...Just remove it if not needed and you are good to go!
You should also follow answers provided from above.
In order to troubleshoot this (at least in laravel 6):
The action property inside Route.php has all the info needed. A better error message should be possible to provide by laravel.
What I did was to add a dd($this->action) just before the exception is thrown here:
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Routing/Route.php#L917
With that in place I could easily pinpoint the location, in my case api.php and lines 22-24:
array:6 [
"middleware" => "api"
"domain" => "local-api.mydomain.com"
"uses" => Closure()^ {#6497
class: "App\Providers\RouteServiceProvider"
this: App\Providers\RouteServiceProvider {#5743 …}
file: "./routes/api.php"
line: "22 to 24"
}
"namespace" => "App\Http\Controllers"
"prefix" => null
"where" => []
]
This is how I solved mine.
Navigate to routes directory
Then open api.php
comment code that looks like this:
Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });
Then run
php artisan optimize
check that your web.php file has this extension
use Illuminate\Support\Facades\Route;
my problem gone fixed by this way.

LARAVEL 5.2 - How to access login page as default page

I just need to know how i can set the login page as default page of my site.
Route::get('/', function () {
return view('welcome');
});
I need something like this:
Route::get('/', function () {
return view('auth.login');
});
It's possible?
Thanks
Yes, it's possible, just put this route before all other routes and this will work.
If you're using standard Laravel 5.2 auth system, you can create this route and use it before all other routes:
Route::get('/', 'Auth\AuthController#getLogin');

Redirect to Login if user not logged in Laravel

i am new to laravel,
i have code in my controller's __construct like
if(Auth::check())
{
return View::make('view_page');
}
return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');
its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.
I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.
Route::filter('auth', function() {
if (Auth::guest())
return Redirect::guest('login');
});
Please help me to resolve this issue.
Laravel 5.4
Use the built in auth middleware.
Route::group(['middleware' => ['auth']], function() {
// your routes
});
For a single route:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Laravel docs
Laravel 4 (original answer)
That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:
Route::group(array('before' => 'auth'), function(){
// your routes
Route::get('/', 'HomeController#index');
});
Or for a single route:
Route::get('/', array('before' => 'auth', 'uses' => 'HomeController#index'));
To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.
To avoid code repetition, You can use it in middleware. If you are using the Laravel build in Auth, You can directly use the auth middleware as given,
Route::group(['middleware' => ['auth']], function() {
// define your route, route groups here
});
or, for a single route,
Route::get('profile', function () {
})->middleware('auth');
If you are building your own, custom Authentication system. You should use the middleware which will check the user is authenticated or not. To create custom middleware, run php artisan make:middleware Middelware_Name_Here and register the newly created middleware.
It's absolutely correct what other people have replied.
This solution is for Laravel 5.4
But just in case, if you have more than one middleware applying to routes, make sure 'auth' middleware comes in the end and not at the start.
Like this:
Route::prefix('/admin')->group(function () {
Route::group(['middleware' => 'CheckUser', 'middleware' => 'auth'], function(){
});
});
Route::middleware(['auth'])->group(function () {
Route::get('dashboard','BackendController#dashboard')->name('dashboard');
});
This entry in the web.php route will take the user [who is not logged in] to the login page if (s)he tries to access a 'protected' URL, "dashboard" in this case.

Resources