Axios post is not submitting in laravel - ajax

I am sending the axios request to laravel login controller.
Axios code
attemptLogin()
{
axios.post('/login',
{email:this.email, password:this.password, remember_me:this.remember_me},
{ headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
}).then((resp) => {
console.log(resp);
// location.reload();
}).catch(error => {
this.errorMessage = error.message;
console.error("There was an error!", error);
})
}
Login Controller code
protected function authenticated(Request $request, $user)
{
// return "Login successfull";
return view('home');
}
I don't what's happening, no error is displaying the console.

Is the browser showing anything? From what you have pointed out, you should ensure that the request is hitting the login function in the LoginController. You must be hitting that trait class and then your request is processed.
class LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}

Actually am answering this my self because I find the exact problem,
Am doing mistake in axios syntax,
correct syntax is below
attemptLogin()
{
axios.post('/login', {
email:this.email, password:this.password, remember_me:this.remember_me
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
}

Related

How to create a login function with Laravel API and VUE client

I am making an application in VUE in which users must log in to access the information.
The login process is done through a Laravel API that will collect the information from a database.
To send the data from the VUE form I do the following in the VUE api:
import axios from 'axios';
const baseURL = 'http://batoilogic.my/api/';
export default {
login(credentials){
return axios.get(baseURL+'login/'+ credentials)
}
}
And in Laravel I have created a LoginController, with the function that will validate the credentials sent by VUE:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return $credentials;
} else {
return $credentials;
}
}
The problem is that no data is being passed from VUE to Laravel. I don't know where I have the problem. It may not be the correct way to send the information.
I need help.
axios.post(baseURL+'login/', {
email: this.email,
password: this.password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

How to return errors in Laravel Custom Request to Ajax

I made custom request as following.
class CustomRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rule['name']='required';
$rule['email'] = 'required|email';
return $rule;
}
}
How can I return validation errors in ajax?
When I didn't use custom request, I returned errors like this.
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'name'=>'required',
'email'=>'required|email'
]
if($validation->fails())
{
return response()->json([$errors=>$validation->errors()]);
}
return response()->json(['status'=>'success']);
}
So here instead of Request, if I use CustomRequest then how can we catch errors?
Another thing.
In custom request rule, how can we get request input values?
public function rules()
{
$rule['name']='required';
if($this->input('phone')) {
$rule['phone'] = 'integer';
}
$rule['email'] = 'required|email';
return $rule;
}
$this->input('phone') Is this right?
Hope to give me answer to my 2 questions.
the error will be either in your error call back function or catch callback depends on how you make ajax call.
eg.
$.ajax({
url: "/test",
type: "post",
data: {foo:'test'} ,
success: function (response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
var data = jqXHR.responseJSON;
console.log(data.errors);// this will be the error bag.
}
for FormRequest I think your code is not correct
public function rules()
{
return [
'title' => 'required',
'body' => 'required',
];
}
This will do the validation. You do not really need to access the input value as Laravel does it for you. But for some reason, if you really want it you can always use the global helper function request()->input('title');

Laravel Passport: Unable to access user data and redirected to login page

I am successfully getting an access and refresh token, but my problem is when I try to return the user. I have this code inside my routes/api.php file
Route::middleware('auth:api')->group(function() {
Route::get('/user', function() {
return $request->user();
});
});
You are returning $request->user() but you are not passing any Request to function.
Change this:
Route::middleware('auth:api')->group(function() {
Route::get('/user', function() {
return $request->user();
});
});
to
Route::middleware('auth:api')->group(function() {
Route::get('/user', function(Request $request) {
return $request->user();
});
});

Put method yields HTTP 405 (method not allowed) but works in Postman (HTTP 500)

I have created an addition to the profile settings page in Spark. The vue code:
Vue.component('update-mail-settings', {
props: ['user'],
data() {
return {
form: new SparkForm({
type: ''
})
};
},
mounted() {
this.form.mailsettings = this.user.mailsettings;
},
methods: {
update() {
Spark.put('update-mail-settings', this.form)
.then(response => {
Bus.$emit('updateUser');
});
}
}
});
I've created a route:
Route::put('/update-mail-settings', 'SettingsController#updateMailSettings');
and the Controller to handle the request. I disabled CSRF checking and as can be seen in the code beneath, also the auth middleware:
class SettingsController extends Controller{
public function __construct(){
//$this->middleware('auth');
}
public function updateMailSettings(Request $request)
{
$request->user()->forceFill([
'mailsettings' => $request->mailsettings
])->save();
return Redirect::back()->with('success', 'Successfully updated mailsettings');
}
}
I didn't show the blade with radio buttons but that doesn't seem like the source of the error.
Interestingly, when I monitor the requests in my Nginx log files I see a 405 error if I click on the update button on the website but if I use Postman, it yields a 500 code (after which it fails since it cannot assign the mailsettings variable --> "Call to a member function forceFill() on null")
Anyone have any idea?

Alert not appearing if i put the route under auth middleware group

I am not allowing the user to submit the form if not logged in. So, giving the alert to login.
Jquery and Ajax
$(document).on('submit', '.bet', function (e)
{
e.preventDefault();
var frm = $(this);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
dataType: 'json',
success: function (data)
{
if(data == 'notloggedin')
{
alert('You must login first!');
}
else if(data==true)
{
swal('Bet Success! The details has been sent to your email!');
}
else if(data=='dateexpired')
{
swal('The match bet time expired!');
}
}
});
});
Controller:
public function store(Request $request)
{
if($request->ajax())
{
if(!Auth::check())
{
echo json_encode('notloggedin');die;
}
....
This went all good. But, if I put this route under auth middleware the alert is not appearing. And in the developer's tool i see unauthorized action. Yes. it is obvious but i still want the alert to appear.
Route::group(['middleware' => ['auth']], function () {
Route::post('/bet/store','BetController#store');
});
The Error is not shown because if the auth middleware fails the response indicates that the request was not successful ( so success method gets not executed ). In this case you have to use .fail() method.
var jqXHR = $.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
dataType: 'json',
success: function (data)
{
if(data == 'notloggedin')
{
alert('You must login first!');
}
else if(data==true)
{
swal('Bet Success! The details has been sent to your email!');
}
else if(data=='dateexpired')
{
swal('The match bet time expired!');
}
}
});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {
if(jqXHR.status == 401) {
alert('unauthorized');
}
});
that's because request is returned (401) from the middleware and controller action is never executed. also middleware is right place for this check why don't you return unauthorised response from auth middleware ? something like this
App\Http\Middleware\Auth
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response()->json(['notloggedin']);
}
return redirect()->guest('login')->withErrors(['You must login first.']);
}
return $next($request);
}
please note that this will return a status 200 for ajax request but I see you are using success function so it would work. You can also return a 401 with
if ($request->ajax()) {
return response('Unauthorized.', 401);
}
and use error method on jQuery

Resources