I'm learning Laravel and I have a problem returning the old inputs to the form.
ERROR:
TokenMismatchException in VerifyCsrfToken.php line 67:
ROUTES - all in the file
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('artigo');
$artigo = \App\Comentario::find(2)->artigo;
var_dump($artigo->title);
$comentarios = \App\Artigo::find(1)->comentario;
foreach($comentarios as $comentario){
var_dump($comentario->body);
}
});
Route::post('/', function(){
$rules = array(
'title'=>'required|max:10',
'body'=>'required|max:4'
);
$validator = Validator::make($_POST,$rules);
if($validator->fails())
return Redirect::to('/')->withInput()->withErrors($validator->errors());
return 'yooo';
});
});
BLADE VIEW
<!DOCTYPE html>
<html>
<body>
<form method="post" action="/">
<input type="text" name="title" placeholder="titulo" value="{{ old('title') }}">
<input type="text" name="body" placeholder="body">
<input type="submit" value="go">
</form>
</body>
</html>
Any help?
ATENTION: im not using sessions yet
Assuming you are using version 5.2 this is might be because your requests are not utilising the sessions. In Laravel 5.2 Sessions are available only if you are using the web middleware.
You should include all routes using sessions within a middleware group called web which is defined in app/Http/Kernel.php under $middlewareGroups
Route::group(['middleware' => ['web']], function () {
// Routes using sessions
});
Related
Auth::user() has a POST request to an external website with the following:
postfile.blade.php
<form action="{{ url('https:www.external.com/api/') }}" method="POST" align="center">
#csrf
#method('POST')
<input type="hidden" name="Data1" value="{{ $Data1}}">
<input type="hidden" name="Data2" value="{{ $Data2}}">
<input type="hidden" name="Data3" value="{{ $Data3}}">
<input type="hidden" name="ReturnURLOK" value="{{ url('/success') }}">
<input type="hidden" name="ReturnURLError" value="{{ url('/fail') }}">
<button type="submit" value="POST TO API">PROCEED/button>
</form>
After which, https:www.external.com/api/ provides a POST request back to Auth::user() url wherein the data are saved on database.
Controller:
public function postfiles(Request $request)
{
$request->session()->put('user_id',Auth::user()->id);
return view('postfile');
}
public function parse(Request $request)
{
$files = File::create([
'Data4' => $request->input('Data4'),
'Data5' => $request->input('Data5'),
'Data6' => $request->input('Data6'),
]);
$data = array(
'Data4' => $request->input('Data4'),
'Data5' => $request->input('Data5'),
'Data6' => $request->input('Data6'),
);
Auth::loginUsingId($request->session()->get('user_id'));
return view('success')->with($data);
}
The data are being saved correctly but in the success.blade.php I'm getting an error when I try to display the data on the blade.
Error is
Trying to get property 'username' of non-object
success.blade.php
<div class="container">
<div>
<h3>CONGRATULATIONS {{ Auth::user()->username}}!</h3>
<h2>The following Data has been saved</h2>
{{ $Data4}}
{{ $Data5}}
{{ $Data6}}
</div>
</div>
Routes:
Route::group(['middleware' => ['auth', 'activated', 'currentUser']], function () {
Route::get('postfile', 'App\Http\Controllers\FileController#postfiles')->name('postfile');
Route::POST('success', 'App\Http\Controllers\FileController#parse')->name('parse');
});
It seems the user's session is somehow lost and Auth::user() becomes null after being redirected back during the POST request from the external website.
i dont know why your logged-in user is lost but:
one solution i can say is that you can save id of that user somewhere like coockie or session and after redirecting back from your api, you get that id and re-login that user
I have one problem, why when I accessing the login/register page always given Route [login] is not defined I already try to search for my problem and nothing result happen, I will give my detail in bellow.
User Controller :
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
in that case, I wanna get the token and user detail after successful login, and it's working I got the token and I got the user detail, but when I logout and back into the login or register page, it's error, and for the message Route [login] is not defined, but when I delete the __construct() it's working, but when I login again with my same account, the token and detail user is giving null value, I will give my route detail in the bellow.
Route :
Route::get('/', function () {
return redirect('auth');
});
Route::get('auth', 'UserController#viewLogin');
Route::get('register', 'UserController#viewRegister');
Route::get('dashboard', 'DashboardController#view');
Route::group(['prefix' => 'auth'], function () {
Route::post('login', 'UserController#login');
Route::post('logout', 'UserController#logout');
Route::get('user-profile', 'UserController#userProfile')->middleware('jwt.verify');
});
Update Login Post :
$user_data = [
'email' => $email,
'password' => $password,
'is_active' => 1
];
$user_credentials = JWTAuth::attempt($user_data);
if (!$user_credentials) {
return response()->json([
'error_message' => 'Your account is not registered yet, please register first'
], 401);
} else {
return response()->json([
'user' => JWTAuth::user(),
'token' => $user_credentials,
'success_message' => "Login Successfuly",
]);
}
Form Login :
<form action="javascript:;" method="POST" autocomplete="off">
#csrf
<div class="form-group">
<label class="font-weight-normal">Email</label>
<div class="input-group">
<input type="email" class="form-control" name="email" placeholder="user#mail.com">
<div class="input-group-append">
<div class="input-group-text input-group-email">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="text-danger" id="email-err"></div>
</div>
<div class="form-group">
<label class="font-weight-normal">Password</label>
<div class="input-group">
<input type="password" class="form-control" name="password" placeholder="********">
<div class="input-group-append">
<div class="input-group-text input-group-password">
<span class="fas fa-eye clicked" id="show-hide"></span>
</div>
</div>
</div>
<div class="text-danger" id="password-err"></div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" id="login-process" class="btn btn-block" disabled>Sign In</button>
</div>
</div>
</form>
Javascript :
$("#login-process").on('click', function () {
const emailValue = $("input[name='email']").val();
const passwordValue = $("input[name='password']").val();
$.ajax({
url: "auth/login",
method: "POST",
async: true,
data: {
email: emailValue,
password: passwordValue,
},
success: function (success) {
// describe one by one success method
const accessToken = success['token'];
const successMessage = success['success_message'];
localStorage.setItem('monitoring-barang', accessToken);
window.location.replace('dashboard');
},
});
});
This error is probably related to your XHR request not having the correct Accept header (which should be application/json).
This will make the auth middleware respond, but even though you combined it with api, the lacking Accept header will make the web middleware group respond with it's authentication.
This will effectively fire the redirectTo method in app/Http/Middleware/Authenticate.php where, on line 18, there's a reference to the route named login, a route you have explicitly not added by adding the except parameter to the middleware method in your controller.
The solution is to either comment out redirect out, make a dummy route for the purpose or implement a better strategy like Sanctum
I have routes setup as
// ----------------------- USER ROUTES -----------------------
Route::group(['prefix' => 'v1/user', 'middleware' => 'throttle:5'], function(){
Route::post('login', 'UserController#login');
});
Route::group(['prefix' => 'v1/user', 'middleware' => 'throttle'], function(){
Route::post('checkuser', 'UserController#checkuser');
Route::post('checkmail', 'UserController#checkmail');
});
HTML as
<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
{!! csrf_field() !!}
And I am getting Method not found error
I know somewhere route is not correct, but how to correct it?
In your case it should be {{ url('v1/user/login') }}.
To avoid using url() you can leverage named routes.
https://laravel.com/docs/5.2/routing#named-routes
When I submit the form, I get this error and the page automatically reloads, but the url in the browser then shows my route and content that I posted in the form. Then, if I go ahead and submit again without reloading the page it works just fine. Could it be that I'm not posting the token itself? I have added the meta tag to the head.
<meta name="csrf-token" content="{{ csrf_token() }}" />
JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#postForm').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
$.ajax({
type: "POST",
url: "/post/"+profileId,
data: {post:body, profile_id:profileId},
success: function(data) {
console.log(data);
}
});
});
Route:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
Controller:
public function postMessage(Request $request, $id)
{
if(Request::ajax())
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
$newMessage = Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
View:
<form role="form" action="#" id="postForm">
<div class="feed-post form-group">
<textarea class="form-control feed-post-input" id="postbody" name="post"></textarea>
<div class="btn-bar">
<button type="submit" class="btn btn-default btn-post"></button>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</form>
UPDATE:
So, the log says that "Request::ajax() should not be called statically" in my controller. I removed that code and it works fine now. However, I want to know if removing it is ok to do of if there's a better way to resolve this. Thanks!
ANSWER: It works by changing
if (Request::ajax()){
// code...
}
to
if ($request->ajax()){
// code...
}
Change Request::ajax() to $request->ajax()
You are doing an AJAX post – you are not supposed to be redirected anywhere at all. If there is an error – you should only see it in Developers Tools in your browser.
Try adding:
$('#postForm').submit(function(e) {
e.preventDefault();
...
}
So that browser doesn't post the form instead of your AJAX call. Also try fixing your header case: X-CSRF-TOKEN to X-CSRF-Token
Also, your postMessage() method doesn't return anything at all. You should probably notify the user of the result there or just return $newMessage.
Hello i use same script for Laravel 4.2 and Laravel 5.1 and problem is for Laravel 4.2 work perfectly, but on Laravel 5.1 i can't understand why it's return bad result
Problem is why I got $request->ajax() false for Laravel 5.1?
routes.php
Route::post('/upload-image', [
'as' => 'upload-image-post',
'uses' => 'PageController#profileImage'
]);
PageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PageController extends Controller
{
public function profileImage(Request $request)
{
//here is problem
//result good: (Laravel 4.2 shows true)
//result bad: (Laravel 5.1 shows false)
var_dump($request->ajax());
}
}
upload-image.blade.php (js)
<script>
jQuery(document).ready(function($) {
$('#upload_image').click(function(event) {
$('#image').trigger('click');
});
$('#image').change(function(event) {
/* Act on the event */
$('#imageform').submit();
});
$('#imageform').ajaxForm({
beforeSubmit: function() {
},
success: function(msg) {
},
error: function(request, status, error) {
},
complete: function(xhr) {
if(xhr.status != 401) {
$('#image').val('');
result = xhr.responseText;
result = $.parseJSON(result);
if( !$.isEmptyObject(result.file_base_url) ) {
var img = new Image();
img.onload = function() {
$('#register_profile_photo').attr('src', img.src);
$('#register_profile_photo').attr('alt', result.image_alt);
//spinner.stop();
$('#upload-image-error').text('');
}
img.src = result.file_base_url;
} else {
$('#upload-image-error').text(result.image[0]);
}
}
}
});
});
upload-image.blade.php (html)
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="{!! route('upload-image-post') !!}">
{!! csrf_field() !!}
<div style="display:none;">
<input type="file" name="image" id="image" placeholder="Please choose your image" >
</div>
</form>
<div class="profile-img">
<img style="float: right" id="register_profile_photo" src="default.png" alt="Default image">
<div style="float: right" class="img-edit">Edit picture</div>
</div>
PS. If you test for laravel 4.2 this code need change from "{!! .. !!}" to "{{ .. }}"
I do not think this problem is caused by Laravel version. Laravel sources show, that ajax() call is propagated to Symfony's request component. And that source changed good 5 years back.
You should trace if X-Requested-With header is sent to your application in both cases. You can also set breakpoint to Symfony\Component\HttpFoundation\Request::isXmlHttpRequest() and see what you have in headers.