Axios returning HTML in response instead of data - laravel

I want to ask for help regarding Axios' response to my POST request in the login route via Laravel. It returns HTML of the homepage in data when it authenticated the user (or it finds the user in the database). Please see the response screenshot below:
May I just ask for the solution to my problem? Here are the necessary codes and the versions that I am using:
Tools
VueJS: v3.0.5
Axios: 0.19
Laravel: 5.8
Codes
Login.vue (script)
import axios from 'axios'
export default {
data() {
return {
csrfToken: '',
loginObj: {
username: '',
password: '',
remember: false,
},
message: '',
}
},
created() {
this.csrfToken = document.querySelector('meta[name="csrf-token"]').content;
},
methods: {
signIn() {
console.log(this.loginObj)
axios.post('login', this.loginObj).then(res => {
console.log(res)
})
.catch(error => {
console.log(error.response)
})
}
}
}
Login.vue (template)
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header bg-orange"><h3 class="text-center my-4">Hello!</h3></div>
<div class="card-body p-0">
<div class="row">
<div class="col-lg-6 d-none d-lg-block">
<div class="login-image-wrap text-center">
<img src="/img/ahrs_logo_trans.png" class="login-img" alt="AKB Logo">
</div>
</div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Sign In</h1>
</div>
<form name="loginForm" #submit.prevent="signIn">
<input type="hidden" name="_token" :value="csrfToken">
<div class="form-group">
<label class="small mb-1" for="inputUsername">Username</label>
<input class="form-control py-4" v-model="loginObj.username" id="inputUsername" type="text" placeholder="Enter username" required autofocus>
</div>
<div class="form-group">
<label class="small mb-1" for="inputPassword">Password</label>
<input class="form-control py-4" v-model="loginObj.password" id="inputPassword" type="password" placeholder="Enter password" required>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" v-model="loginObj.remember">
<label class="form-check-label text-small" for="remember">
Remember Me
</label>
</div>
</div>
<div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0">
<a class="small" href="password.html">Forgot Password?</a>
</div>
<hr />
<div>
<button type="submit" class="btn bg-yellow btn-block font-weight-bold">LOGIN</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
LoginController.php
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// override in the AuthenticatesUsers function username()
public function username()
{
return 'username';
}
Thank you for your help.

You will probably need to tell Laravel that you want to return the User as JSON if it's an ajax request.
You can do this by adding the following to your LoginController:
protected function authenticated(Request $request, $user)
{
if ($request->ajax()) {
return $user;
}
}
You may also need to set the X-Requested-With header that is usually set in the default bootstrap.js file that comes with Laravel so that Laravel knows it's an ajax request:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Obviously, if this line is already there and you're still including the bootstrap file in your bundle you can ignore this.

Related

Using Vue, Inertia, Laravel, how do I update a file object in an edit component?

I currently have an edit page, which hits an update function to update the Itinerary object when changed.
On this page, if I click submit straight away, and dd() the $request from the ItineraryController, it returns all of the existing form data, as expected.
If I edit the data in the fields, then submit it, it returns successfully with a full request object as expected.
If, however, I choose a file in the "replace file" selector, the entire request object shows as null when the form is submitted, and thus can't be submitted.
How can I adjust this so that the "replace file" input is operational, and fills the request object with the existing itinerary data?
Component:
<template>
<form #submit.prevent="submit">
<div class="row w-75 m-auto">
<h1>Edit Itinerary</h1>
<div class="col-md-6">
<label for="title">Title</label>
<input v-model="form.title" class="form-control" name="title" placeholder="Itinerary Title" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="gen_narrative">Narrative</label>
<textarea v-model="form.gen_narrative" class="form-control" name="gen_narrative" placeholder="Itinerary Narrative"></textarea>
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label>Current Photo</label>
<img :src="assetUrl(props.itinerary.f_photo)" alt="featured photo" />
</div>
</div>
<br />
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="fileChange" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="authorid">Author Name</label>
<input v-model="form.authorid" class="form-control" name="authorid" placeholder="Author Name" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<button class="btn btn-primary" type="submit">Edit Itinerary</button>
</div>
</div>
</form>
</template>
<script setup>
import { useForm } from "#inertiajs/inertia-vue3";
function assetUrl(path) {
return process.env.MIX_BASE_URL + "storage/" + path;
}
function fileChange(event) {
form.f_photo = event.target.files[0];
}
let props = defineProps({
itinerary: {
type: Object,
required: true,
},
});
let form = useForm({
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops,
});
let submit = () => {
console.log(form.title);
form.patch("/itineraries/" + props.itinerary.id);
form.reset();
};
console.log(form);
</script>
<style scoped></style>
Controller:
public function edit($id)
{
$itinerary = Itinerary::find($id);
return Inertia::render('Itineraries/Edit', [
'itinerary' => $itinerary,
]);
}
public function update(Request $request, $id)
{
$itinerary = Itinerary::find($id);
$itinerary->title = $request->title;
$itinerary->gen_narrative = $request->gen_narrative;
//upload the photo
if ($request->hasFile('f_photo')) {
$itinerary->f_photo = $request->f_photo->store('public/itinerary_photos');
}
$itinerary->authorid = $request->authorid;
$itinerary->save();
return redirect('/itineraries');
}
let form = useForm({
forceFormData: true,
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops
})
The best I can come up with is writing your file upload inline
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="form.f_photo = event.target.files[0]"/>
</div>
</div>
Based on this example in official documentation you can do
<input type="file" #input="form.f_photo = $event.target.files[0]" />
Your issue is probably because Inertia does not natively support uploading files using a multipart/form-data request for the put, patch or delete methods, as is stated here (in the "Multipart limitations" section).
An alternative way is to submit without form helper using post method with the _method attribute of 'put', like:
Inertia.post("/itineraries/" + props.itinerary.id", {
_method: 'put',
f_photo: form.f_photo,
})

Laravel 8 Form Request Validation Redirect to Index page instead same page and show error

On localhost all is good, but when I deploy the application to the server not working. If form request validation fails instead of bringing me back to the same page and showing an error, it redirects me to the index page.
config.blade.php
<form method="POST" action="{{ route('config.update', $config->id) }}">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col">
<label class="col-form-label">Name</label>
<input id="name" type="text" class="form-control" name="name" value="{{ $config->name }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Address</label>
<input id="address" type="text" class="form-control" name="address" value="{{ $config->address }}">
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Phone</label>
<input id="phone" type="tel" class="form-control" name="phone" value="{{ $config->phone }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">E-mail</label>
<input id="email" type="email" class="form-control" name="email" value="{{ $config->email }}" required>
</div>
</div>
<div class="form-group row mt-4 mb-0">
<div class="col-md-12">
<button type="submit" class="btn btn-primary button-full-width">Save changes</button>
</div>
</div>
</form>
web.php
Route::resource('/admin/config', 'Admin\ConfigController');
ConfigController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\ConfigServices;
use App\Http\Requests\ConfigRequest;
use App\Models\Config;
class ConfigController extends Controller
{
protected $configServices;
public function __construct(ConfigServices $configServices) {
$this->middleware('auth');
$this->configServices = $configServices;
}
...
public function update(ConfigRequest $request, $id)
{
$config = $this->configServices->updateConfigById($request, $id);
return redirect()->back();
}
...
}
ConfigRequest - here is the problem
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConfigRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'address' => 'nullable|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:9|max:15',
'email' => 'required|email:rfc',
];
}
}
Form Request return to index page instead same page. On localhost working everything, but when I deploy the app to server a problem arises.
When data on form request validated correct return me back on the same page and show success, but when form request failing redirect mine for some reason to the index page.
A problem arises in Laravel 8, this code worked well in previous Laravel versions.
Can someone help me, please?
In your custom request you need:
/**
* The URI that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirect = '/dashboard';
or
/**
* The route that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirectRoute = 'dashboard';
You can find more in the docs.
In the docs for older versions of Laravel these properties don't exist.
Do you have error parts in your blade?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#if ($message = Session::get('unique'))
asdsad
#endif
#endforeach
</ul>
</div>
#endif

middleware conflicts with controller __construct middleware (request validation error not working)

I am using middleware for user roles.
But when I am using middleware in Controller __construct method, request validation does not work properly. It doesnt show any errors, session error bag returns null. I am not able to see any errors when form submit. But when I have disabled middleware in construct I can see request validation errors.
web.php middleware + controller _construct middleware = request validation doesnt works.
web.php middleware + without _construct middleware = works fine.
without web.php middleware + _construct middleware = works fine.
I showed the details in my codes.
I tried every method for a week but I couldn't solve it.
I look forward to your help sincerely.
web.php
Route::group(['middleware' => ['client.role:paying']], function () {
Route::get('/pay_section', 'HomepageController#showPaySection');
Route::get('/pay_success', 'HomepageController#showPaySuccess');
Route::get('/pay_error', 'HomepageController#showPayError');
Route::post('/pay_section', 'HomepageController#doPaySection');
});
HomepageController (like this my form request validation doesnt works because of middleware)
public function __construct()
{
$this->middleware(function ($request, $next) {
$client = auth()->guard('client');
if ($client->check()){
$request->session()->put('client_id', $client->user()->id);
}else{
$request->session()->put('client_id', -1);
}
$this->_cid = $request->session()->get('client_id'); // client
View::share(['cid' => $this->_cid]);
return $next($request);
});
}
HomepageController (like this my codes works perfect. I am able to see request validation errors there is no problem.)
public function __construct()
{
$this->_cid = 2; // client
View::share(['cid' => $this->_cid]);
}
Middleware ClientRole.php
public function handle($request, Closure $next, ...$roles)
{
$currentRole = array();
$client = auth()->guard('client');
if ($client->check()){
$currentRole[] = 'client';
}else{
$currentRole[] = 'guest';
}
if (session()->has('shop_cart')) {
$currentRole[] = 'shopping';
}
if (session()->has('order')) {
$currentRole[] = 'paying';
}
$currentRole[] = 'paying';
foreach($roles as $role) {
if(in_array($role, $currentRole))
return $next($request);
}
return redirect('/');
}
HomepageController form action
public function doPaySection(CreditcardRequest $request)
{
$validated = $request->validated();
// it doesnt show any errors when form empty. But it should be.
// without middleware it shows error on my view when form empty.
}
View
<div class="messages">
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Error!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
</div>
<form action="{{ action('HomepageController#doPaySection') }}" method="post"
class="needs-validation" novalidate>
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<label for="ccname">Name on card</label>
<input type="text" class="form-control" name="cc_name" id="ccname" placeholder="" value="" required>
<small class="text-muted">Full name as displayed on card</small>
<div class="invalid-feedback">
Name on card is required
</div>
</div>
<div class="col-md-6 mb-3">
<label for="ccnumber">Credit card number</label>
<input type="text" class="form-control" name="cc_number" id="ccnumber" placeholder="" value="" >
<div class="invalid-feedback">
Credit card number is required
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 mb-3">
<label for="ccexp">Expiration</label>
<input type="text" class="form-control" name="cc_exp" id="ccexp" placeholder="" value="1209" required>
<div class="invalid-feedback">
Expiration date required
</div>
</div>
<div class="col-md-3 mb-3">
<label for="cccvv">CVV</label>
<input type="text" class="form-control" name="cc_cvv" id="cccvv" placeholder="" value="333" required>
<div class="invalid-feedback">
Security code required
</div>
</div>
</div>
<hr class="mb-4">
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">
<i class="fa fa-check"></i> Submit
</button>
</form>
You may set SESSION_DRIVER=file in you .env file
Then run php artisan config:clear
Seems related

Laravel : no errors and no update on database happens after saving the edit

I have two tables, user and technicien, with a one to one relation. After editing technicien information through edit form and saving, no update happens on database and no errors as well.
Here is my code:
controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')-
>name('technicien.update');
You just need to pass parameters to update function.
Read docs
public function update(Request $request, $id)
{
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update([
'nom' => $request->nom,
'premon' => $request->premon,
'email' => $request->email
]);
return redirect('/technicien');
}
Also from the docs
You should define which model attributes you want
to make mass assignable. You may do this using the $fillable property
on the model.

stripe token is not passing

I have an application built in Laravel 4 and uses this package
I am following this tutorial
This is the error I am getting http://postimg.org/image/c4qwjysgp/
My issue is $token is not correctly passing or the $token is empty.
I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing.
Here is the view
#extends('layouts.main')
#section('content')
<h1>Your Order</h1>
<h2>{{ $download->name }}</h2>
<p>£{{ ($download->price/100) }}</p>
<form action="" method="POST" id="payment-form" role="form">
<input type="hidden" name="did" value="{{ $download->id }}" />
<div class="payment-errors alert alert-danger" style="display:none;"></div>
<div class="form-group">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>Expires</span>
</label>
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" />
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" />
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Submit Payment</button>
</div>
</form>
#stop
Here is the route
Route::post('/buy/{id}', function($id)
{
Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key'));
$download = Download::find($id);
//stripeToken is form name, injected into form by js
$token = Input::get('stripeToken');
//var_dump($token);
// Charge the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $download->price,
"currency" => "gbp",
"card" => $token,
"description" => 'Order: ' . $download->name)
);
// If we get this far, we've charged the user successfully
Session::put('purchased_download_id', $download->id);
return Redirect::to('confirmed');
} catch(Stripe_CardError $e) {
// Payment failed
return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.');
}
});
Here is the js
$(function () {
console.log('setting up pay form');
$('#payment-form').submit(function(e) {
var $form = $(this);
$form.find('.payment-errors').hide();
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message).show();
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.get(0).submit();
}
}
Here is the stripe.php in package
<?php
return array(
'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO',
'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG'
);
Seems like the Config::get might be wrong.
It would have to be written this way.
Stripe::setApiKey(Config::get('stripe.api_key'));
I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.

Resources