Reputation: 1482
If I have a custom config file with custom options where is the best place to put those options? Should I create middleware and those options to that?
Basically what I have is a custom config file that has an option to turn off or on a certain section of the application. If it's set to True routes and the controllers for those pages will be accessed. If False then they are not accessed.
I have all the pieces in place and I am able to use Config::get("customer.mode")
in sections of my code. However, I am just not sure of the best practice for this situation
Upvotes: 0
Views: 1234
Reputation: 4557
This is the best way to do what you want.
Customer Middleware AuthAccess.php
<?php namespace App\Http\Middleware;
use myconfig; // your file or class.
use Closure;
class AuthAccess{
public function __construct() {
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
// your logic here to auth access to the route
if ( true ){
$response = $next($request);
return $response;
}
else {
return redirect() -> to('/'); // or show error page.
}
}
}
Add the new middleware to Kernel.php like this
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'auth.access' => 'App\Http\Middleware\AuthAccess',
];
Don't forget to dump-autoload..
Now you can apply the new middleware to a single route or a group of routes. This will keep your code clean and organized. Hope this help.
Upvotes: 0
Reputation: 120
It seems this rule is something like permission or business rule, and in my opinion, Controller is not the best place for this.
Also try to find a solution to not repeat this Config::get("customer.mode")
code, so you may need to create a class what responsible for to get the cusomer.mode...
Collect the routes or group them with Route:group
and create a middleware for this rule.
Upvotes: 0
Reputation: 3251
The best place to put it is in the config folder in your project root. Just return an associative array with your configs in it, and to access it you can just use the Config facade. For example
config/urls.php
inside urls.php
return [
'service_url' => 'http://server.com'
]
Then in your application, to access this value
Config::get('urls.service_urls');
or
config('urls.service_urls');
The key there is that the first part of the config string is the codefilename that you put the config array in, then on down the chain.
So in short, yes this is best practice.
Upvotes: 1