Laravel custom guard exclude routes - laravel

I have created a custom auth guard for laravel 5.8 and is registered to the AuthServiceProvider.
Using the constructor definition below inside a controller, I want to exclude specific routes from getting authenticated (like register):
$this->middleware('protect', ['except' => 'store']);
protect is just an alias for the middleware doing the job
'protect' => \App\Http\Middleware\GauthJwt::class,
But this seems to have no effect as my guard gets hit anyway.
Do I have to somehow register or parse the routes in my guard?
Am I missing something on the way laravel handles custom guards?
Routes using this middleware:
| GET|HEAD | api/users | users.all | App\Http\Controllers\Api\User\UserController#all | api,protect |
| POST | api/users | users.register | App\Http\Controllers\Api\User\UserController#store | api |

Related

laravel 8 404| not found error and route list issue

I was working on my project and everything was normal, suddenly I lost the connection and my server stopped working giving me error while trying this link http://127.0.0.1:8000/
I tried php artisan optimize, and also checked my route list but it gives me only below line:
--------+----------+---------------------+-----------------------------+------------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+---------------------+-----------------------------+------------------------------------------------------------+------------+
| | GET|HEAD | sanctum/csrf-cookie | generated::RGn651ZoIReNs5HE | Laravel\Sanctum\Http\Controllers\CsrfCookieController#show | web
+--------+----------+---------------------+-----------------------------+------------------------------------------------------------+--------
and this is my web file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ProjectReportController;
use App\Models\Project;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
//Route::get('/home',[HomeController::class,'index']);
Route::middleware('auth')->group(function(){
//
////////////////Home Controller///////////
Route::get('/', 'HomeController#index');
//Route::get('/',[HomeController::class,'index']);
Route::get('about', 'HomeController#about')->name('aboutUsers');
Route::get('contact', 'HomeController#contact');
//Route::get('/welcome', 'HomeController#welcome')->name('welcome');
Route::get('/users', 'HomeController#users');
Route::get('users/{id}','HomeController#detail');
Route::view('adduser','users.add_user'); //insert data
Route::post('adduser',[HomeController::class,'addUsers']); //for insert user
////////////////Project Controller///////////
//Route::get('/ad_ajxsrch', 'ProjectController#list'); //changed tp from get to post
Route::view('add','addproject'); //insert data
Route::post('add',[ProjectController::class,'addProject']); //for insert data
Route::get('delete/{id}',[ProjectController::class,'delete'])->middleware(CheckUser::class);
Route::get('updateReport/{id}','ProjectController#showData');
Route::post('updateReport','ProjectController#update');
Route::get('new/{id}','ProjectController#detail');
Route::get('p_reports/{id}','ProjectController#note');
//Route::get('new',[ProjectController::class,'searchData'])->name('sm_search');//changed tp from get to post
Route::get('gn_ajxsrch',[ProjectController::class,'searchData'])->name('sm_search'); //pagination reload
Route::get('projectReport','ProjectController#download_pdf');
Route::get('new/{id}/search_result','ProjectReportController#detail_pdf');
///////Manager Resource////////////////
Route::resource('manager','ManagerController');
///////Report Resource////////////////
Route::resource('report','ProjectReportController');
Route::get('new/{id}/report',[ProjectController::class,'reports_num']);
/////////////////Joint table//////////////////
//Route::get('/show',[ProjectReportController::class,'show'])->name('adm_search');
//Route::post('/re_search',[ProjectReportController::class,'searchRow']);
Route::get('test',[ProjectReportController::class,'test']);
//Route::resource('/new','ProjectController');
Route::get('ad_search',[ProjectReportController::class,'ad_search'])->name('web.search');
Route::get('ajaxpagi-show',[ProjectReportController::class,'re_report']);
Route::get('ad_ajxsrch',[ProjectReportController::class,'show_srch'])->name('adm_search');
//Route::get('gn_ajxsrch',[ProjectController::class,'searchData'])->name('sm_search');
});
?>
Try to clear the route cache once, with: php artisan route:clear.
The underlying issue might be a permission problem on the caches.

Implicit Route Model Binding returns empty model in package

I'm building a laravel package the encapsulates a rest api, and I'm running into some issues with implicit route model binding. All I'm getting back when trying to retrieve a single record is an empty array. The id that i'm trying to retrieve is present in the database (its the only record in the table) Using debugbar, it looks like its not running the query, which implies that the route binding is failing before it has a chance to run (more on that at the bottom).
api.php:
Route::apiResources([
'trackers' => TrackerController::class,
'tracker/entry' => TrackerEntryController::class,
'tracker/types' => TrackerTypeController::class
]);
pertinent artisan route:list output:
| Method | URI | Middleware |
+-----------+-----------------------+------------+
| GET|HEAD | tracker/entry/{entry} | |
| GET|HEAD | tracker/types/{type} | |
| GET|HEAD | trackers/{tracker} | |
+-----------+-----------------------+------------+
Show method from TrackerTypeController:
use Oxthorn\Trackers\Models\TrackerType as Type;
public function show(Type $type)
{
return $type;
}
So, as far as I see, my code is using the correct naming scheme for implicit route binding.
If I change the controller show method to this:
public function show(Type $type, $id)
{
$type2 = Type::findOrFail($id);
return [
[get_class($type), $type->exists, $type],
[get_class($type2), $type2->exists],
];
}
I get this output:
[
[
"Oxthorn\\Trackers\\Models\\TrackerType",
false,
[]
],
[
"Oxthorn\\Trackers\\Models\\TrackerType",
true
]
]
This seems to mimic the behavior in this StackOverflow issue: Implicit Route Model Binding, where the last posted theory was that SubstituteBindings middleware was not running. I'm not sure at this point what steps I need to take to ensure its running before my code execute, so I am here asking for advice on where to go from here.
You know, sleeping on a problem does wonders. For anyone that runs into this same issue while developing a package, I had to change my route code to this to solve the issue:
Route::apiResource('trackers', TrackerController::class)->middleware('bindings');
Route::apiResource('tracker/entry', TrackerEntryController::class)->middleware('bindings');
Route::apiResource('tracker/types', TrackerTypeController::class)->middleware('bindings');

How to resolve a "MethodNotAllowedHttpException" error in Laravel?

I am developing a passport API in Laravel. I am getting a "MethodNotAllowedHttpException".
I don't get any idea, what fix do I have to do.
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('register', 'Api\Auth\RegisterController#register');
Route::post('login', 'Api\Auth\LoginController#login');
Route::post('refresh', 'Api\Auth\LoginController#refresh');
Route::middleware('auth:api')->group(function () {
Route::post('logout', 'Api\Auth\LoginController#logout');
Route::get('posts', 'Api\PostController#index');
});
this error can occur due to request type (GET / POST) mismatch in your route and the request type in your API call or form tag in your view
check if the request type matched in your route file and in your APIcall
See, you use 'post' method in your route:
Route::post('register', 'Api\Auth\RegisterController#register');
And the browser's default is 'get'. Are you trying to show a registration form or you are submitting a form to that route.
Either you should change that route to GET or create another route to show the page, then submit the form as post to the intended route

Controller actions appearing in "artisan route:list" as Closures

I'm at a loss. I'm working on upgrading an application to Laravel 5.4, but on the way (5.2.45) I've got something weird happening with several routes. I had 3 Route::controller() calls in routes.php, and I've converted all of them to explicit routes since ::controller() has been dropped. Now the new routes from one of the ::controller() calls are working fine, the routes from the other two are not, reporting action not found.
Looking at examples, here's one that is working:
\Route::get( 'account/edit', array( 'as'=>'account.edit', 'uses'=>'AccountController#getEdit' ) );
and here is one that is not:
\Route::get( 'recent/clear', array( 'as'=>'recent.clear', 'use'=>'RecentController#getClear' ) );
For completeness sake, here are the applicable Controller sections
class AccountController extends Controller {
public function getEdit()
{
$roles = Role::getSelectList();
$districts = District::getSelectList();
return \View::make('accountedit', array( 'editUser' => \Auth::user(), 'roles'=>$roles, 'districts'=>$districts ));
}
}
class RecentController extends Controller {
public function getClear()
{
\Session::forget( 'recent' );
return \Redirect::to('/main')->with( array( 'alerts'=>array( ErrorHelper::alert('success','Success','The Recent list has been cleared.') ) ) );
}
}
The most direct sign something weird is going on is when I run artisan route:list. Here are the two applicable lines from the results:
| Method | URI | Name | Action |
+-----------+---------------+---------------------------------+-------------------------------------------------+
| GET|HEAD | account/edit | account.edit | App\Http\Controllers\AccountController#getEdit |
| GET|HEAD | recent/clear | recent.clear | Closure |
I have no idea why recent.clear is showing up as a Closure. Any thoughts as to what's wrong? FWIW, I have identical namespacing on both controllers, which are both in the Http\Controllers directory.
Oh heck, uses vs. use. In the words of Grover, "I am so embarrassed..."

Is there any possibility to reduce routes in laravel4

I want to know is there any possibility to reduce routes for same controller in laravel4.
Here is my route:
Route::get('emp/add-employee/','EmpController#addEmployee');
Route::post('emp/add-employee/','EmpController#addEmployee');
Route::get('emp/edit-employee/{id}','EmpController#editEmployee');
Route::post('emp/edit-employee/{id}','EmpController#editEmployee');
Route::get('emp/view-employee/{id}','EmpController#viewEmployee');
is there any posibility to do reduce...?
Your route actions look like the ones you'd find in a RESTful Resource Controller. So you could use this:
Route::resource('emp', 'EmpController', array('only' => array('create', 'store', 'edit', 'update', 'show')));
This will of course require you to rename the controller methods accordingly and the route paths will be a little different, but you'd have a more compact route definition and consistent naming. Below are the routes that are generated by the Route::resource definition above.
+-----------------------------+---------------+-------------------------+
| GET emp/create | emp.create | EmpController#create |
| POST emp | emp.store | EmpController#store |
| GET emp/{id} | emp.show | EmpController#show |
| GET emp/{id}/edit | emp.edit | EmpController#edit |
| PUT emp/{id} | emp.update | EmpController#update |
+-----------------------------+---------------+-------------------------+
So you'd have to rename your controller method names like so:
GET : addEmployee() -> create() // shows the add form
POST: addEmployee() -> store() // processes the add form when submitted
GET : editEmployee() -> edit() // shows the edit form
POST: editEmployee() -> update() // processes the edit form when submitted
GET : viewEmployee() -> show()
You could use controller routes.
Route::controller('emp', 'EmpController');
Now you just have to rename the functions within your controller to also represent the method used like this:
public function getAddEmloyee()
public function postAddEmloyee()
public function getEditEmployee($id)
etc.
See also the Laravel docs for controllers
Yes, use Route::match(). This will allow you to specify GET and POST in a single route call, like so:
Route::match(['GET', 'POST'], 'emp/edit-employee/{id}','EmpController#editEmployee');
You can also use Route::all() which will match any type request, which includes GET and POST and also any other HTTP verbs that may be specified, if that's what you want.

Resources