Laravel feature test using middleware - laravel

I'm trying to make a feature test for the start page of my Laravel application.
Route:
Route::domain('{subdominio}.'.env("APP_DOMAIN"))->middleware('mapNumserie')->group(function () {
Route::get('/', 'FarmaciaController#show')->middleware('modomtofarmacia')->name('inicio');
})
For some reasons, I use a middleware mapNumserie where I map the subdomain aganist a serial number $idfarmacia in order to use it after in controller:
public function handle($request, Closure $next){
try{
$route = $request->route();
$idfarmacia = \App\Farmacia::where('subdominio', $route->subdominio)->value('numserie');
$route->setParameter('idFarmacia', $idfarmacia);
$route->forgetParameter('subdominio');
}
catch (\Exception $e){
abort(404);
}
return $next($request);
}
In my ModoMtoFarmacia middleware I just check that an app instance is not in maintenance mode or disabled:
public function handle(Request $request, Closure $next){
$farmacia = \App\Farmacia::find($request->idFarmacia);
if($farmacia->inactiva){
abort(404);
}
if(!$farmacia->modomantenimiento){
return $next($request);
}
else{
return response()->view('errors.503')->setStatusCode(503);
}
}
In my controller symply get some data using this $idfarmacia and return a view:
public function show(Request $request, $idfarmacia) {
$data =
//Query...
if($data){
return view('inicio', ['data' => $data]);
}
else{
abort(404);
}
}
With a very simple test method I hope to validate a 200 response :
public function test_example(){
$response = $this->get('http://mysubdomain.domain.prj');
$response->assertStatus(200);
}
But when I run the test I get:
Expected response status code [200] but received 404.
The used URL works correctly in web environment, but the test fails. Where am I wrong?

Finally a found the problem in my phpunit.xml settings, which caused an error in the first query (also in any other), in this case the one found in the MapNumserie middleware:
$idfarmacia = \App\Farmacia::where('subdominio', $route->subdominio)->value('numserie');
I had to set up properly the values of DB_DATABASE and DB_CONNECTION

Related

How to fix this, i try to load dashboard route when the auth middleware is true

But when authentication was success, it shown error Route [/db1] not defined. I hace declared db1 route, but this route can access only if user has session. Anyone can tell me what wrong with my code?
this is my route:
Route::group(['middleware' => ['userSession']], function() { Route::get('/db1', [WasteController::class, 'db1'])->name('db1'); });
this is my kernel in middlewareGroup:
'userSession' => [ \App\Http\Middleware\CheckUserSession::class, ],
this is my middleware:
public function handle($request, Closure $next) {
if ($request->session()->get('status') != 'true') {
//status user cannot be found in session
return redirect('/');
}
return $next($request);
}
i have tried but it show error db1 route not defined
Did you try this?
public function handle($request, Closure $next) {
if ($request->session()->get('status') = 'true') {
//status user cannot be found in session
return $next($request);
}
return redirect('/');
}

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

"Trying to get property 'headers' of non-object" Middleware\VerifyCsrfToken.php:180

I wrote my custom middleware, but when it is executed, the error appears.
Middleware:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Employee;
class CheckConfirm
{
public function handle($request, Closure $next)
{
if(Auth::check())
{
$id = Auth::id();
$empl = Employee::where('user_id','=', $id)->get();
if($empl->isEmpty())
{
return route('confirm');
}
else
{
dump($empl);
return $next($request);
}
}
else
{
return route('login');
}
}
}
When I try something like this:
if($empl===null)
{
return route('confirm');
}
сondition just doesn't work.
In this case, database queries are executed successfully.
Here is the error page with dump
Your middleware must return a Response object, or $next($request). As written, when not logged in or when $empl is empty, your middleware is just returning a string, not a redirect.
Update your returns to:
return redirect()->route('confirm');
and
return redirect()->route('login');
respectively.
It is very hard to fix, I tried to do it with App\Http\Middleware\VerifyCsrfToken::except, but not work.
My solution to this problem was creating a redirect to another route using App\Exception\Handler::render method.
if ($exception->getMessage() == "Trying to get property 'headers' of non-object") {
return redirect()->route('my.default.page');
}
Replace this line:
$empl = Employee::where('user_id','=', $id)->get();
if($empl->isEmpty()){ ... }
With this:
$empl = Employee::where('user_id', $id)->first();
if($empl){ ... }
Then dd() for each line, see where it fails. There may be an missing csrf token or the user is not logged..

Only load route with existent parametre

Im doing a crud, i want to show item data using id, i have this in web.php:
Route::get('update/{id}', 'CrudController#update');
How can I deny that the user changes the id in the path to one that does not exist? That shows only those that exist and those that do not, that do not load?
In your update method, you can do the following:
public function update($id)
{
MyModel::findOrFail($id);
//...perform other actions
}
It will throw a 404 response if the requested $id is a non-existent one.
Then you can catch it if you want in the render() method of app\Exceptions\Handler.php:
use Illuminate\Database\Eloquent\ModelNotFoundException;
.
.
.
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
if ($request->wantsJson()) {
return response()->json([
'data' => 'Resource not found'
], 404);
} else {
abort(404);
}
}
return parent::render($request, $exception);
}
Or, If you do not want to go through all the trouble of configuring it in the handler, you could also do:
public function update($id)
{
if (! $model = MyModel::find($id)) {
abort(404);
}
//...perform other actions with $model
}
The abort(404) method takes the user to the default Page not found page of laravel, which is an appropriate thing to do.

How to use custom middleware with Laravel 404 exception

In my Laravel 5.2 app I have custom middleware called 'cart' that I use to keep track of the users cart contents across different routes.
It looks like this:
class CartMiddleware
{
public function handle($request, Closure $next)
{
$cart = new Cart();
$cart_total = $cart->total();
view()->composer(['layouts.main'], function ($view) use ($cart_total) {
$view->with('cart_total', $cart_total);
});
return $next($request);
}
}
Route::group(['middleware' => ['cart']], function () {
Route::get('cart', 'CartController#show');
});
When ever my app raises a 404 exception the 404.blade.php view cannot render because it is missing the $cart_total that is supplied by the 'cart' middleware.
Is there a way to assign this 'cart' middleware to my exception?
if ($e instanceof HttpException) {
if ($request->ajax()) {
return response()->json(['error' => 'Not Found'], 404);
}
return response()->view('errors.404', [], 404);
}
return parent::render($request, $e);
At Laravel 5.4 and probably some older ones you can modify the file app/exceptions/Handler.php and the function render like this:
if( is_a( $exception, \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class ) ) {
return redirect()->route( 'error_404' );
}
// ... old code in the function ...
in this way every 404 errors are redirected to certain real route that acts like other routes of site.
You may also submit any data from current request to show a reasonable error at the target.

Resources