I have created a Middleware via php artisan make: middleware AdminCheck
Registered it in kernal.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminCheck::class,
'auth' => \App\Http\Middleware\Authenticate::class,
//default middlewares.....
];
In web.php this is how I'm using it for all my routes
Route::prefix('/app')->middleware('admin')->group(function () {
Route::post('/create_tag', 'AdminController#addTag');
Route::get('/get_tags', 'AdminController#getTag');
Route::post('/edit_tag', 'AdminController#editTag');
});
Here is my The Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
class AdminCheck
{
public function handle(Request $request, Closure $next)
{
Log::info("Middleware Reached");
dd("Middleware Reached");
if (!Auth::check()) {
//l redirect to login
return redirect('/login');
}
return $next($request);
}
}
The middleware is working since the routes are still accessed even without login and there's nothing in the log and its not die dumping either
For similar issues in the future, kindly check your cache, you can do so by doing
php artisan about
To clear your cache you can do:
php artisan cache:clear
php artisan view:clear
php artisan config:clear
php artisan route:clear
It will list what is cached, if you are going to be making any changes to route/config/views you should clear the cache and cache again.
Related
I'm trying to use simple laravel api for getting and sending requests, after define this api routes in api.php:
Route::prefix('Api/v1')->group(function () {
Route::any('login', 'Api\v1\AuthController#login');
Route::any('register', 'Api\v1\AuthController#register');
});
and creating AuthController in app/http/controller/Api/v1 directory:
class AuthController extends Controller
{
public function login()
{
dd(request()->all());
}
public function register()
{
dd(request()->all());
}
}
i get 404 error on this link:
http://127.0.0.1:8000/Api/v1/login
how can i resolve this problem?
Routes in api.php are automatically prefixed with /api. Currently, your routes are:
http://127.0.0.1:8000/api/Api/v1/login
http://127.0.0.1:8000/api/Api/v1/register
So navigating to http://127.0.0.1:8000/Api/v1/login is a 404.
If you remove /Api, and just use Route::prefix('/v1') ... then you should have no issue.
Also, always double check your routes with php artisan route:list to see what's wrong.
The API Routes are already prefixed by /api . I think the correct structure you'd looking for would be
Route::prefix('v1')->group(function () {
Route::any('login', 'AuthController#login');
Route::any('register', 'AuthController#register');
});
This way, you're calling the methods Login and Register from you /Controllers/AuthController file with the route
http://127.0.0.1:8000/api/v1/login
You can use many ways to define routes for API in laraval > routes > api.php file.
In this i'm going to explain how we can use routes group in the laraval..
Route::group([
'namespace' => 'Customers', //namespace App\Http\Controllers\Customers;
'middleware' => 'auth:api', // this is for check user is logged in or authenticated user
'prefix' => 'customers' // you can use custom prefix for your rote {{host}}/api/customers/
], function ($router) {
// add and delete customer groups
Route::get('/', [CustomerController::class, 'index']); // {{host}}/api/customers/ this is called to index method in CustomerController.php
Route::post('/create', [CustomerController::class, 'create']); // {{host}}/api/customers/create this is called to create method in CustomerController.php
Route::post('/show/{id}', [CustomerController::class, 'show']); // {{host}}/api/customers/show/10 this is called to show method in CustomerController.php parsing id to get single data
Route::post('/delete/{id}', [CustomerController::class, 'delete']); // {{host}}/api/customers/delete/10 this is called to delete method in CustomerController.php for delete single data
});
You can create controller using artisan command with default methods
php artisan make:controller Customers/CustomerController --resource
Class App\Http\Controllers\HomeController does not exist
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class HomeController extends Controller
{
public function index()
{
$posts = Post::paginate(10);
return view ('pages.index', ['posts' => $posts]);
}
public function show($slug)
{
$post = Post::where('slug', $slug)->firstOrFail();
return view ('pages.show', compact('post'));
}
}
web.php
Route::get('/', 'HomeController#index');
Route::get('/post/{slug}', 'HomeController#show')->name('post.show');
Route::group(['prefix'=>'admin','namespace'=>'Admin'], function(){
Route::get('/', 'DashboardController#index');
Route::resource('/categories', 'CategoriesController');
Route::resource('/tags', 'TagsController');
Route::resource('/users', 'UsersController');
Route::resource('/posts', 'PostsController');
});
At the beginning a new authorization controller appeared, I turned off the KG and removed
Five most important commands if your Laravel is not working as expected after some modifications in .env or database folder or because of any other modifications. Here is full explanation: https://www.youtube.com/watch?v=Q1ynDMC8UGg
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear
Please have a look at this thread: https://stackoverflow.com/a/43041479/6935763
Run this command to clear all compiled files:
php artisan clear-compiled
See more as this commands here:
https://laravel.com/docs/5.8/artisan
Hope this helps!
In some cases adding the controller directory resolves this issue. Please check the controller directory and make changes according to that.
Normally it is App\Http\Controllers
if so, then you can try with changing the route code to the following:
Route::get('/', 'App\Http\Controllers\HomeController#index');
Route::get('/post/{slug}', 'App\Http\Controllers\HomeController#show')->name('post.show');
check your controller directory.
I'm trying to test my api and for this matter I don't need authentication for my api all I want to do is to share my published posts with api but I get 404 page.
Code
controller
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;
class PostController extends Controller
{
public function index(){
return Post::orderby('id', 'desc')->where('status', '=', '1')->get();
}
public function single($slug){
return Post::where('slug', $slug)->where('status', '=', '1')->firstOrFail();
}
}
api.php (routes folder)
Route::get('posts', 'API\PostController#index');
Route::get('posts/{slug}', 'API\PostController#single');
I tried to access my api posts with url like: http://newapp.test/api/posts and it returns 404 error.
Any idea?
Update
api.php
<?php
use Illuminate\Http\Request;
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
Route::get('posts', 'API\PostController#index');
Route::get('posts/{slug}', 'API\PostController#single');
Leave all things as it is and RUN Command
php artisan route:clear
Run command php artisan route:list. It will show you list of available routes in your application. In this way, you could first verify the existing routes and the ones you are trying to access.
My API mistake was: redirecting back
if($validator->fails()){ return redirect()->back()->withInput()->with('error',$validator->errors()->first());}
corrected by: returning a JSON
if($validator->fails()){ return $this->responseWithError($validator->errors()->first()); }
responseWithError is a helper method that returns JSON in a certain structure
I ran php artisan make:auth in Laravel 5.6 as it is well known this did generated a HomeController.php file.
Inside that:
public function index(){
return view('home');
}
and Route::get('/home', 'HomeController#index')->name('home'); route definition into web.php.
But http://homestead.test/home URI redirect to http://homestead.test/login due RedirectIfAuthenticated.php middleware. So RedirectIfAuthenticated.php works as global middleware instead route middleware although is defined in $routeMiddleware property in Kernel.php.
Why does this happen?
What do I not know?
If you look at the constructor of the controller that was created it is using the auth middleware.
$this->middleware('auth');
If you look at your Kernel.php at $routeMiddleware:
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
This doesn't involve RedirectIfAuthenticated at all. That would redirect any users who are already authenticated away from a route. The auth middleware redirects everyone who isn't authenticated to a route, 'login'.
I have following Controller Action Method.
namespace App\Http\Controllers\API\SportsType;
class SportsTypeApiController extends \App\Http\Controllers\Controller
{
public function apiSportsTypes() {
return 1;
}
}
Here is the route
Route::group(['prefix' => 'api/v1'], function () {
Route::get('/apiSportsTypes', 'API\SportsType\SportsTypeApiController#apiSportsTypes');
});
It gives 404 error. Am I missing something? Please let me know if you need more details.
It was happening because the routes were using cache. Due to that new routes were not even appearing in command prompt even if I was typing below command.
php artisan route:list
Then I had to remove the route cache by using the below command
php artisan route:clear
and now everything is working fine.