Access a URL Parameter in a Route Prefix from Middleware - php

I am struggling to access a route prefix parameter from my middleware.
Given this URL: http://www.example.com/api/v1/campaign/40/status, and the following route:
Route::group( [
'prefix' => 'api/v1'
], function()
{
Route::group( [
'prefix' => 'campaign/{campaign}',
'where' => [ 'campaign' => '[0-9]+' ],
'middleware' => [
'inject_campaign'
]
], function()
{
Route::get( 'status', 'CampaignController#getStatus' );
} );
} );
How do I access the campaign parameter (40 in the example URL) from my inject_campaign middleware? I have the middleware running fine but cannot work out how to access the parameter.
Calling $request->segments() in my middleware gives me the parts of the route but this seems a fragile way of accessing the data. What if the route changes?

You can do it using shorter syntax
You can use:
echo $request->route()->campaign;
or even shorter:
echo $request->campaign;

Got it!
$request->route()->getParameter('campaign')

Related

Disable Auth Register route in Laravel 8?

I need to disable my register route in Laravel 8. Tried
Auth::routes([
'register' => false,
'login' => false,
]);
but the application threw up an error.
RuntimeException
In order to use the Auth::routes() method, please install the laravel/ui package.
If anyone points out what needs to change, will be grateful.
Thanks
Laravel 8 uses fortify authentication. To disable registration from your laravel app, you need to disable it from fortify, which is located on /config/fortify.php
'features' => [
// Features::registration(), // disable here
Features::resetPasswords(),
Features::emailVerification(),
Features::updateProfileInformation(),
Features::updatePasswords(),
Features::twoFactorAuthentication(),
],
At the end of my routes/web.php was the following line:
require __DIR__.'/auth.php';
In routes/auth.php are listed all additional routes for user login/register/logout. Just comment out or remove /register route from there.
In addition, be sure to disable related routes, in routes/web.php :
Route::get('/register', function() {
return redirect('/login');
});
Route::post('/register', function() {
return redirect('/login');
});
I changed according feature tests in tests/Feature/RegistrationTest.php to try to keep work clean so I needed those redirections.
Remove the registration routes from config/auth.php and then create a config/fortify.php (paste the content from: vendor/laravel/fortify/config/fortify.php) which will override the default settings.
Inside config/fortify.php comment out the first element of features array (Features::registration()) then run php artisan optimize to clear config cache and routes cache.
Now all your removed routes should return 404, you can also check if those still exist with php artisan route:list
config/fortify.php:
<?php
use Laravel\Fortify\Features;
return [
'guard' => 'web',
'middleware' => ['web'],
'passwords' => 'users',
'username' => 'email',
'email' => 'email',
'views' => true,
'home' => '/home',
'prefix' => '',
'domain' => null,
'limiters' => [
'login' => null,
],
'features' => [
//Features::registration(),
Features::resetPasswords(),
Features::emailVerification(),
Features::updateProfileInformation(),
Features::updatePasswords(),
Features::twoFactorAuthentication(),
],
];
Just use:
Auth::routes(['register' => false]);
Do not break your head with different versions of packages and Laravel. Because maybe you don't have fortify.php in your config, or using different packages. All routes are in routes/web now. Just go there and force that '/register' sends to login or any other view you want to:
Route::any('/register', function() {
return view('auth.login');
});
That way you maintain out of reach that feature, but close for when you need it.
Remove this code from routes/auth.php
Route::get('/register', [RegisteredUserController::class, 'create'])
->middleware('guest')
->name('register');
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest');
Just put this in your /routes/web.php:
Route::any('/register', [App\Http\Controllers\HomeController::class, 'index']);

Optional route parameters not working in Lumen 5.7

I had defined my route and controller as following
$router->group(['prefix' => 'api/v1'], function ($router) {
$router->group(
['middleware' => 'auth'], function() use ($router) {
$router->get('/order/get-order-status/{order_id}[/{account_id}]'
, [
'uses' => 'Api\V1\OrderController#getOrderStatus'
, 'as' => 'getOrderStatus'
]
);
});
});
following is the function defination
public function getOrderStatus($orderId, $accountId = false)
{
// my code goes here
}
Here the problem is whenever, I skip the optional account_id from the route, then passed order_id is assigned to the 2nd parameter of the function i,e. accountId. If I pass both params then everything is working as expected. I'm just confused whether something is wrong in my configuration or Lumen itself have some issue with optional route params?
Consider I had triggered http://localhost/lumen/api/v1/order/get-order-status/ORD1234 then ORD1234 is assigned to accountId and '0' is assigned to orderId
optional route parameters are given like below,
$router->get('/order/get-order-status/{order_id}/{account_id?}' // see the ? mark
though I am not sure why 0 is assigned to the orderId,
and usually, the first parameter to the controller method is a request object, so you can easily identify what are the things that the request contains.
public function getOrderStatus(Request $reqeust, $orderId, $accountId = false)
move out your optional parameter route outside the group
$router->group(['prefix' => 'api/v1'], function ($router) {
$router->get('/order/get-order-status/{order_id}[/{account_id}]'
, [
,'middleware' => 'auth',
'uses' => 'Api\V1\OrderController#getOrderStatus'
, 'as' => 'getOrderStatus'
]
);
or like this following code
$router->get('api/v1/order/get-order-status/{order_id}[/{account_id}]',
['uses' => 'Api\V1\OrderController#getOrderStatus',
'middleware' => 'auth',
'as' => 'getOrderStatus'
]
);
I think you should use optional parameter like
{account_id?} rather then [/{account_id}]

Groups in group on routing Laravel

I really need help!
On the Laravel 5.3, it seems that a group of routes into an another group isn't working for me. Is there any solution to make it work ? Or do I have to write my routes in another way ? This is the way I write my routes:
Route::group([
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
Route::group([
'prefix' => 'admin'
], function () {
// General Settings
Route::get('settings', [
'as' => 'admin.settings',
'uses' => 'AdminController#showSettings'
]);
});
});
I am using a prefix in the first group for the multiple language and the another group is for the admin section. I want an url like this : /en/admin/settings
The problem is solved! It did not work because I had used another route in which there was an paramater before the group of admin section ex:
Route::get('activate/{code}', [
'as' => 'auth.activation',
'uses' => 'RegistrationController#getActivate'
]);

The redirect_uri URL must be absolute facebook Laravel

I want to make login with facebook using Socialite in laravel. First I set the route function:
Route::group(['middleware' => ['web']], function(){
Route::get('auth/facebook', [
'as' => 'auth-facebook',
'uses' => 'usersController#redirectToProvider'
]);
Route::get('auth/facebook/callback', [
'as' => 'facebook-callback',
'uses' => 'usersController#handleProviderCallBack'
]);
});
And then I make function in the user controller:
public function redirectToProvider(){
return Socialite::driver('facebook')->redirect();
}
But I'm getting the error The redirect_uri URL must be absolute
Any ideas?
Looks like you are missing the configuration.
You will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file, and should use the key facebook, twitter, linkedin, google, github or bitbucket, depending on the providers your application requires. For example:
'facebook' => [
'client_id' => '',
'client_secret' => '',
'redirect' => '',
],
Add callbackURL along with clientID and clientSecret
fb": {
"clientID": "*************************",
"clientSecret": "*******************************",
"callbackURL": "//************/auth/facebook/callback",
"profileFields": ["id", "displayName", "photos"]
},

How to differentiate parameter vs declared route when routing?

Having the next routes:
Route::get('/apartment/{apartment_name}', 'ApartmentController#getApartmentByName');
Route::get('/apartment/create', [
'uses' => 'ApartmentController#create',
'as' => 'apartment.create'
]);
Route::get('/apartment/edit', [
'uses' => 'ApartmentController#edit',
'as' => 'apartment.edit',
]);
How could I make a difference between the routes
myapp.com/apartment/create and myapp.com/apartment/beach-apartment
I would like to search by the apartment's name with the same URI prefix (apartment/) but with this code I'm always calling the parameter route.
It is because whatever is being called, create or edit, is being matched within the parameter one, /apartment/{apartment_name}, as create or edit equals to the apartment_name.
Just move the parameter one to the lower most line within that block.
Route::get('/apartment/create', [
'uses' => 'ApartmentController#create',
'as' => 'apartment.create'
]);
Route::get('/apartment/edit', [
'uses' => 'ApartmentController#edit',
'as' => 'apartment.edit',
]);
Route::get('/apartment/{apartment_name}', 'ApartmentController#getApartmentByName');
With this configuration, if the /apartment/create or /apartment/edit is not matched, then it will match /apartment/{apartment_name}.

Categories