I am pretty new to Laravel. So I have a Laravel Vue app where i want to hide a view.blade only in my production environment and not on staging , i tried with the config file view but i didn't succeed.
Can anyone help me please ?
Thank you
One possible solution would be to use an if statement for the view. It's difficult to give a more contextual answer without more context.
example below:
<template>
<view v-if="inProduction"></view>
</template>
export default {
computed: {
inProduction(){
return process.env.NODE_ENV === "production";
}
}
}
You could do a conditional route middleware too so it just checks the config file (cached) for the env. Then you can send them anywhere you want if someone tried to hit that route.
If you're trying to hide a full route on certain env best way would be to create a Middleware like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AppEnv
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, $env)
{
if(config('app.env') == $env) {
return $next($request);
}
abort(404);
}
}
You'll have to register this middleware on the app/Http/Kernel $routeMiddleware array
Then you can use it like this:
Route::view('/', 'welcome')->middleware(['env:local'])
(Change local for the env where you want to show this route)
Related
Thanks in advance for helpful advice. I am using Laravel Livewire for creating components and Jetstrap for authentication for those routes that require it.
At the moment I only have one route set up for testing authentication, yet after I have logged in to view that route, I get the following error:
Too few arguments to function Livewire\LivewireManager::mount(), 0 passed in /var/www/mvp/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 261 and at least 1 expected
This seems to be originating from the LivewireManager class, inside the getInstance() function:
public function getInstance($component, $id)
{
$componentClass = $this->getClass($component);
throw_unless(class_exists($componentClass), new ComponentNotFoundException(
"Component [{$component}] class not found: [{$componentClass}]"
));
return new $componentClass($id);
}
It seems to be expecting a component argument from the Facade class in /vendor/laravel/framework/src/Illuminate/Support/Facades/, but isn't getting the component it needs. I checked the page code, and there is definitely a component there.
The Facade function creating the error:
/**
* Handle dynamic, static calls to the object.
*
* #param string $method
* #param array $args
* #return mixed
*
* #throws \RuntimeException
*/
public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
And the page that's supposed to be loading its component:
#extends('layouts.app')
#section('content')
#livewire('component')
#stop
Is there a simple way to fix the problem? Or am I missing something?
I got same error like what you get when i try to passing parameter and then i'm solving the problem by following the documentation with changing the way to render livewire component from using blade directive #livewire() into <livewire: >
I am learning Slim Framework v4 and decided to use Respect\Validation to validate inputted data and have hit a snag where I do not know how to inject the PDO into my custom rule I created.
The idea is to validate some inputs against the database if the provided data exist (or in another instances, if it was inputted correctly). In this specific case, I am tying to validate user's credentials for log in. My idea is this:
AuthController.php:
v::with('app\\Validators\\');
$userValidation = v::notBlank()->email()->length(null, 255)->EmailExists()->setName('email');
EmailExists() is my custom rule.
EmailExists.php:
namespace app\Validators;
use PDO;
use Respect\Validation\Rules\AbstractRule;
class EmailExists extends AbstractRule
{
protected $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function validate($input, $id = null)
{
// a PDO query that checks if the email exists in database
}
}
But I get an error of Too few arguments to function app\Validators\EmailExists::__construct(), 0 passed and exactly 1 expected, which is somewhat expected since the AbstractRule does not have a PDO injected and my class extends it.
So how to inject the PDO interface so that I can use it in my custom rules?
Are you guys using another approach in validating this kind of data? Do note that I am writing an API, so the database validation is somewhat a must and after Googling for past two days, I have no solutions at hand.
I am also using a PHP-DI where I create PDO interface. This is my dependencies.php file:
declare(strict_types=1);
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
use app\Handlers\SessionMiddleware;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
PDO::class => function (ContainerInterface $c) {
$settings = $c->get('settings')['db'];
$db = new PDO("mysql:host={$settings['host']};dbname={$settings['database']};charset={$settings['charset']},{$settings['username']},{$settings['password']}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8',time_zone='{$offset}'");
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $db;
},
'session' => function(ContainerInterface $c) {
return new SessionMiddleware;
}
]);
};
And (part of) index.php:
declare(strict_types=1);
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);
// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);
// Build PHP-DI Container instance
$container = $containerBuilder->build();
// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
// Register middleware
$middleware = require __DIR__ . '/../app/middleware.php';
$middleware($app);
// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
// Add Routing Middleware
$app->addRoutingMiddleware();
// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);
Any help would be appreciated.
Use your user model to count the number of rows in the user table where there is a hit.
If it is not exactly 0, the check returns false, if it is exactly 0, the check passes.
So you don't have to include a PDO at this point. I use Slim 3 and that works quite well.
namespace app\Validators;
use Respect\Validation\Rules\AbstractRule;
class EmailAvailable extends AbstractRule {
/**
* #param $input
*
* #return bool
*/
public function validate ($sInput) {
return User::where('user_email', $sInput)->count() === 0;
}
}
class EmailAvailable extends AbstractRule {
/**
* #param $input
*
* #return bool
*/
public function validate ($sInput) {
return User::where('user_email', $sInput)->count() === 0;
}
}
This is the problem.. I have the next code repeated in different methods and in different controllers.
if (Gate::denies('admin-role')) {
return redirect()->action('HomeController#index')->with('warning','No');
}
If someday I decide change the action route or the message I don't want to go through all methods and change it. Is there a way I can put this code in some part and specify the methods where is going to be applied?
I try to do it with middlewares like this:
$this->middleware('can:admin-role', ['only' => 'index', 'create']);
but I don't know how to custom the redirection.
Use custom middlewares I don't know if its a good idea because then I have to create a middleware for each role(user, admin, superadmin, mixroles, etc).
Create a middleware class and apply that in your routes/route groups, that way you won't have to apply it in individual controllers or their methods.
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Gate::denies('admin-role')) {
return redirect()->action('HomeController#index')->with('warning','No');
}
return $next($request);
}
}
I'm working with Laravel 5 authentification system provided by default.
After logging out, a user is redirected to the root page but I'd like to change that.
I managed to do it for the "login" and "registering" process by defining "$redirectTo" in "AuthController.php". But for "logout", I defined "$redirectAfterLogout" at the same place but it seems to not be taken into account.
Could anyone explain me where is the problem and how to fix it please?
Thanks a lot.
For Laravel 5,
Open AuthController class : app/Http/Controllers/Auth/AuthController.php
Add below property to the class
protected $redirectAfterLogout = 'auth/login';
you can change auth/login with any url.
The redirect after logout is hard coded in the trait AuthenticatesAndRegistersUsers. You can override it in your AuthController by adding this:
public function getLogout()
{
$this->auth->logout();
return redirect('logout');
}
If you don't provide the $redirectAfterLogout attribute, it will use the default which is '/'.
This logic can be found in this class: \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
Having said that, just add this attribute in your AuthController:
protected $redirectAfterLogout = '/afterRedirectURL';
For Laravel 5.5 override logout method inside LoginController. In my case I am redirecting to home route after login.
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect()->route('home');
}
using the built in laravel Auth in the controllers I just override the loggedOut method which triggers after logout to redirect
in the "LoginController.php" which uses
use AuthenticatesUsers;
in the AuthenticatesUsers Trait is a logout method, you can optionally override this or you will see that it triggers a loggedOut method
You can override the logged out method which is default blank and have that redirect
/**
* The user has logged out of the application.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
protected function loggedOut()
{
return redirect()->route('login.show');
}
In App\Controllers\Auth\AuthController, add the following two variables.
protected $redirectTo = '/private_dashboard';
protected $redirectAfterLogout = '/public_homepage';
You get the idea.
I have a same problem in Laravel 5.0. Override a method does the trick.
1) Go to app/Http/Controllers/Auth/AuthController.php
2) Add a new method :
// Override Logout method (define custom url)
public function getLogout()
{
$this->auth->logout();
return redirect('auth/login'); // Your Custom URL
}
it'only laravel versi 5.4 if you want custom redirect url logout,
open /your-project-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
and edit redirect based on you needed
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
I am currently trying to configure a routing option in Symfony2 so /cms will route to /cms/role/view. However, the passing of defaults doesn't seem to work properly.
/src/MyProject/CMSBundle/Resources/config/routing.yml
MyProjectCMS_specific:
pattern: /cms/{page}/{option}
defaults: { _controller: MyProjectCMSBundle:Main:index, page: role, option: view }
requirements:
_method: GET
/src/MyProject/CMSBundle/Controller/MainController.php
<?php
namespace MyProject\CMSBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class MainController extends Controller
{
public function indexAction($page, $option)
{
$response = null;
/* Switch statement that determines the page to be loaded. */
return $response;
}
}
?>
The problem is that when I try to go to `localhost/app_dev.php/cms', it gives me the following error:
Controller "MyProject\CMSBundle\Controller\MainController::indexAction()" requires that you provide a value for the "$page" argument (because there is no default value or because there is a non optional argument after this one).
500 Internal Server Error - RuntimeException
However, if I try to visit localhost/app_dev.php/cms/role or localhost/app_dev.php/cms/role/view, it gives me the correct page. I've tried adding a default route to /cms, but it still gives me the same error. How is this possible and how can I fix this?
Thanks in advance.
I don't know what is the difference between what you wrote and
public function indexAction($page = "role", $option = "view")
but maybe you could try it and tell us.