Laravel Breeze logout redirect on 127.0.0.1 on shared host - laravel

I have domain for example aaa.com. And I deploy Laravel on my webhost succesfully. Login, pages, all things etc. works fine. but whenever I logout it redirects me to 127.0.0.1 not aaa.com. Of course, I have to point out that I am using Laravel Breeze
and here is what I wrote:
my logout form inside any page.
<form method="POST" action="{{ route('logout') }}">
#csrf
<button type="submit" class="underline text-sm text-gray-600 hover:text-gray-900">
{{ __('Log Out') }}
</button>
</form>
My web.php include require __DIR__.'/auth.php'; . Does not contain any logout redirects.
and inside auth.php
Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
and finally AuthenticatedSessionController.php
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
I don't understand why I am being redirected to 127.0.0.1 instead of aaa.com?
Edit:
and forgot to mention my .env file include
APP_URL=https://aaa.com

In .env file, Change APP_URL
APP_URL=http://aaa.com

Thank you to everyone who replied. It fixed itself the next day. It must be something left in the web host's cache, or your browser's. It's not a Laravel thing.

Related

Send parameter by url in login laravel

Take the routes out of the auth and put them in web.php, I want to send a parameter through the url for the login but it throws me an error.
Route::get('login/{url}', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
ErrorException (E_ERROR)
Route [login/{url}] not defined. (View: C:\wamp64\www\portalmecanico_copia\resources\views\auth\login.blade.php)
Previous exceptions
Route [login/{url}] not defined. (0)
When using the route helper you are referencing the route name for the route. In this case the POST route doesn't have a name, so you should name it:
Route::post('login', ...)->name('post-login');
<form method="POST" action="{{ route('post-login') }}" aria-label="{{ __('Login') }}">
Your POST route isn't defining any route parameter so not sure what you want done with the url parameter from the GET route.
If you want to have the GET and POST route for login to take the same parameter you can do that without naming the POST route:
Route::get('login/{url}', ...)->name('login');
Route::post('login/{url}', ...);
<form method="POST" action="{{ route('login', ['url' => ...]) }}" aria-label="{{ __('Login') }}">
if you just want to resolve you error. you have to do this in your form action
<form method="get" action="{{ route('login', ['url' => 'specify the parameter here']) }}" aria-label="{{ __('Login') }}">
the {url} is just like variable.
but if you want to set your form method to post, you have to specified the route name, or you just can do with http://localhost/login

Laravel verfication.resend - The GET method is not supported for this route. Supported methods: POST

Odd question here. Im using the default Auth::routes(['verify' => true]); In Laravel 6. So I register ( Custom registration form ) and all works fine ( added to database etc ) then I am taken to the verification page where it has an email link to resend. When I click this I get:
The GET method is not supported for this route. Supported methods: POST.
The View has this named routed in the link route('verification.resend')
As you can see here. Verify resend is a POST route. So GET method is not allowed. So it should be a form Post instead.
If you are using blade something like this will get you there.
<form method="POST" action="{{ route('verification.resend')) }}">
</form>
Because in laravel 6+ they added this route as a post so you can do it by below code
<a onclick="event.preventDefault(); document.getElementById('email-form').submit();">{{ __('click here to request another') }}
</a>.
<form id="email-form" action="{{ route('verification.resend') }}" method="POST" style="display: none;">
#csrf
</form>

Laravel NotFoundHttpException although route exits

I added a new route as:
Route::post('friendSend/{uid}','FriendController#sendFriendRequest')->name('friends.add');
and called it as a hyperlink to submit form:
<a href="{{route('friends.add',$user->uid)}}"
onclick="event.preventDefault();
document.getElementById('addfriend-form).submit();">
<i class="glyphicon glyphicon-facetime-video" style="color:#F44336;"></i> Add Friend
</a>
<form action="{{route('friends.add',$user->uid)}}" method="post" id="addfriend-form">
{{ csrf_field() }}
</form>
However when I click on the said link, I get redirected to /friendSend with the said error.
the route is visible in:
php artisan route:list
which makes sense since I called it via it's name 'friends.add'. It doesn't even go the controller.
I've already tried the following:
Laravel NotFoundHttpException although route exists
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Friend;
use Auth;
class FriendController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return redirect()->route('home');
}
public function sendFriendRequest($id)
{
echo "hello world";
}
}
Update:
Manually entering the url as /friendSend/2 (or any number for that matter) works.
You are missing a ' in the onclick javascript.
<a href="{{route('friends.add',$user->uid)}}"
onclick="event.preventDefault();
document.getElementById('addfriend-form').submit();">
<i class="glyphicon glyphicon-facetime-video" style="color:#F44336;"></i> Add Friend
</a>
<form action="{{route('friends.add',$user->uid)}}" method="post" id="addfriend-form">
{{ csrf_field() }}
</form>
If this doesn't work, what is the href on the generated page? Do you have multiple of these forms on a single page?
I thing you are doing wrong on set the url in form submit.You are adding route like
href="{{route('friends.add',$user->uid)}}"
Just modified it as
href="{{route('friends.add',['uid' => $user->uid])}}"
You can refer Laravel Named Routes

Logging out via a link in Laravel

I have a "Logout" link in my top navigation bar. I'm wondering how I can make it so that while I'm logged in, it'll log me out when I click on it and return me to the homepage.
To be specific, what changes to which files do I make in Laravel? Also, what code do I need to write in the view, which currently contains just HTML, to trigger this?
When you run php artisan make:auth, the default app.php in Laravel 5.5 does it like this:
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
Edited 28/12/2019: It's work, but This answer contains a serious security issue. Please consider before using it. The Answer by Lucas Bustamante maybe a better choice. Refer to the comment section of this answer.
1) if you are using the auth scaffold that laravel contains. You can do this, in your navigation bar add this:
logout
then add this to your web.php file
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
Done. This will logout you out and redirect to homepage. To get the auth scaffold, from command line, cd into your project root directory and run
php artisan make:auth
2) add this to your navigation bar:
logout
then add this in your web.php file
Route::get('/logout', 'YourController#logout');
then in the YourController.php file, add this
public function logout () {
//logout user
auth()->logout();
// redirect to homepage
return redirect('/');
}
Done.
Read:
https://mattstauffer.co/blog/the-auth-scaffold-in-laravel-5-2
https://www.cloudways.com/blog/laravel-login-authentication/
Use the logout() method:
auth()->logout();
Or:
Auth::logout();
To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session.
if you want to use jQuery instead of JavaScript:
<a href="javascript:void" onclick="$('#logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
As the accepted answer mentions that logging out via GET has side effects you should use the default POST route already created by Laravel auth.
Simply create a little form and submit it via link or button HTML tag:
<form action="{{ route('logout') }}" method="POST">
#csrf
<button type="submit">
{{ __('Logout') }}
</button>
</form>
If you use guard you can logout using this line of code :
Auth::guard('you-guard')->logout();
in laravel 8.x
#csrf
<x-jet-dropdown-link href="{{ route('logout') }}"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Logout') }}
</x-jet-dropdown-link>
</form>

TokenMismatchException in VerifyCsrfToken.php Line 67

I know that this is a known error with things like forms in Laravel. But I am facing an issue with basic authentication in Laravel 5.2.
I created the auth using Laravel;
php artisan make:auth
Now I have the same copy of code on my server and my local. On my local I am getting no issue whatsoever. However on my server, when I try to register a user I get the error saying TokenMismatchException in VerifyCsrfToken.php Line 67
Both my local and server environments are in sync, yet I keep getting the error on registration. Any help on how I can fix this?
I'm assuming you added $this->middleware('auth'); inside the constructor of your controller to get the authentication working. In your login/register forms, if you are using {!! Form::someElement !!}, add the following line at the top as well:
{!! csrf_field() !!}
Or if you are using input tags inside your forms, just add the following line after <form> tag:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Hope this helps.
I had a similar issue and it was an easy fix.
Add this in your HTML meta tag area :
<meta name="csrf-token" content="{{ csrf_token() }}">
Then under your JQuery reference, add this code :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
If you are using the HTML form submit (not AJAX) then you need to put :
{{ csrf_field() }}
inside your form tags.
I was about to start pulling out my hair!
Please check your session cookie domain in session.php config. There is a domain option that has to match your environment and it's good practice to have this configurable with you .env file for development.
'domain' => env('COOKIE_DOMAIN', 'some-sensible-default.com'),
If nothing is working you can remove the CSRF security check by going to App/Http/Middleware/VerifyCsrfToken.php file and adding your routes to protected $excpt.
e.g. if i want to remove CSRF protection from all routes.
protected $except = [
'/*'
];
P.S although its a good practice to include CSRF protection.
You need to have this line of code in the section of your HTML document, you could do that by default , it won't do any harm:
<meta name="csrf-token" content="{{ csrf_token() }}" />
And in your form you need to add this hidden input field:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Thats it, worked for me.
I was facing the same issue with my application running on laravel 5.4
php artisan session:table
php artisan make:auth
php artisan migrate
.. and then following command works for me :)
chmod 777 storage/framework/sessions/
One more possibility of this issue, if you have set SESSION_DOMAIN (in .env) different than HOST_NAME
Happy coding
I have also faced the same issue and solved it later.
first of all execute the artisan command:
php artisan cache:clear
And after that restart the project.
Hope it will help.
Your form method is post. So open the Middleware/VerifyCsrfToken .php file , find the isReading() method and add 'POST' method in array.
There are lot of possibilities that can cause this problem.
let me mention one.
Have you by any chance altered your session.php config file?
May be you have changed the value of domain from null to you site name or anything else in session.php
'domain' => null,
Wrong configuration in this file can cause this problem.
By default session cookies will only be sent back to the server if the browser has a HTTPS connection. You can turn it off in your .env file (discouraged for production)
SESSION_SECURE_COOKIE=false
Or you can turn it off in config/session.php
'secure' => false,
I also get this error, but I was solved the problem. If you using php artisan serve add this code {{ csrf_field() }} under {!! Form::open() !!}
php artisan cache:clear
Clear cache & cookies browser
Using Private Browser (Mozilla) / Incognito Window (Chrome)
Open your form/page and then submit again guys
I hope this is solve your problem.
Make sure
{!! csrf_field() !!}
is added within your form in blade syntax.
or in simple form syntax
<input type="hidden" name="_token" value="{{ csrf_token() }}">
along with this,
make sure, in session.php (in config folder), following is set correctly.
'domain' => env('SESSION_DOMAIN', 'sample-project.com'),
or update the same in .env file like,
SESSION_DOMAIN=sample-project.com
In my case {!! csrf_field() !!} was added correctly but SESSION_DOMAIN was not configured correctly. After I changed it with correct value in my .env file, it worked.
change the session driver in session.php to file mine was set to array.
Can also occur if 'www-data' user has no access/write permissions
on the folder:
'laravel-project-folder'/storage/framework/sessions/
Below worked for me.
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
Have you checked your hidden input field where the token is generated?
If it is null then your token is not returned by csrf_token function.You have to write your route that renders the form inside the middleware group provide by laravel as follows:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('welcome');
});
Here root route contains my sign up page which requires csrf token. This token is managed by laravel 5.2.7 inside 'web' middleware in kernel.php.
Do not forget to insert {!! csrf_field() !!} inside the form..
Go to app/provides.
Then, in file RouteServiceProvider.php, you'll have to delete 'middleware' => 'web' in protected function mapWebRoutes(Router $router)
The problem by me was to small post_max_size value in php.ini.
Put this code in between <form> and </form> tag:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
I had the same issue but I solved it by correcting my form open as shown below :
{!!Form::open(['url'=>route('auth.login-post'),'class'=>'form-horizontal'])!!}
If this doesn't solve your problem, can you please show how you opened the form ?
You should try this.
Add {{ csrf_field() }} just after your form opening tag like so.
<form method="POST" action="/your/{{ $action_id }}">
{{ csrf_field() }}
Are you redirecting it back after the post ? I had this issue and I was able to solve it by returning the same view instead of using the Redirect::back().
Use this return view()->with(), instead of Redirect::back().
For me, I had to use secure https rather than http.
try changing the session lifetime on config/session.php like this :
'lifetime' => 120, to 'lifetime' => 360,
Here I set lifetime to 360, hope this help.
I got this error when uploading large files (videos). Form worked fine, no mismatch error, but as soon as someone attached a large video file it would throw this token error. Adjusting the maximum allowable file size and increasing the processing time solved this problem for me. Not sure why Laravel throws this error in this case, but here's one more potential solution for you.
Here's a StackOverflow answer that goes into more detail about how to go about solving the large file upload issue.
PHP change the maximum upload file size
In my case, I had a problem when trying to login after restarting server, but I had csrf field in the form and I didn't refresh the page, or it kept something wrong in the cache.
This was my solution. I put this piece of code in \App\Http\Middleware\VerifyCsrfToken.php
public function handle($request, Closure $next)
{
try {
return parent::handle($request, $next); // TODO: Change the autogenerated stub
} catch(TokenMismatchException $e) {
return redirect()->back();
}
}
What it does is catching the TokenMismatchException and then redirecting the user back to the page (to reload csrf token in header and in the field).
It might not work always, but it worked for my problem.
Try php artisan cache:clear or manually delete storage cache from server.
If you check some of the default forms from Laravel 5.4 you fill find how this is done:
<form class="form-horizontal" role="form" method="POST" action="{{ route('password.email') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required> #if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
{{ csrf_field() }}
is the most appropriate way to add a custom hidden field that Laravel will understand.
csrf_filed() uses csrf_token() inside as you can see:
if (! function_exists('csrf_field')) {
/**
* Generate a CSRF token form field.
*
* #return \Illuminate\Support\HtmlString
*/
function csrf_field()
{
return new HtmlString('<input type="hidden" name="_token" value="'.csrf_token().'">');
}
}
And csrf_field() method uses session for the job.
function csrf_token()
{
$session = app('session');
if (isset($session)) {
return $session->token();
}
throw new RuntimeException('Application session store not set.');
}
I have same issue when I was trying out Laravel 5.2 at first, then I learnt about {{!! csrf_field() !!}} to be added in the form and that solved it. But later I learnt about Form Helpers, this takes care of CSRF protection and does not give any errors. Though Form Helpers are not legitimately available after Laravel 5.2, you can still use them from LaravelCollective.
Got to your laravel folder :: App/http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
// Pass your URI here. example ::
'/employer/registration'
];
}
And it will exclude this url from the Csrf validation. Works for me.

Resources