when i try to submit a form with Ajax,i get this Error,MethodNotAllowedHttpException No message.
i guess problem is in routing, but when i tested without Ajax it works fine
here is my Ajax code:
$.ajax({
method: 'POST',
url: "{{ route('submitProfile') }}",
dataType: 'json',
data: {_token: CSRF_TOKEN, firstName:firstName, lastName:lastName, email:email, mobile:mobile},
success: function( data ) {
console.log(data);
}
});
my route is:
Route::get('/edit/profile',[
'uses' => 'UserController#getEditProfile',
'as' => 'editProfile'
]);
Route::post('/ajax/edit/profile',[
'uses' => 'UserController#postEditProfile',
'as' => 'submitProfile'
]);
and in my controller i have this functions:
public function postEditProfile(Request $request)
{
$this->validate($request,[
'firstName' => 'required',
'lastName' => 'required',
'email' => 'required|email',
'mobile' => 'required',
]);
$user = \Auth::user();
$user->firstName = $request['firstName'];
$user->lastName = $request['lastName'];
$user->email = $request['email'];
$user->mobile = $request['mobile'];
$user->save();
return response()->json([
'status' => 'its done!'
]);
}
thank you.
Can you try this for your route
Route::post('/ajax/edit/profile',[
'uses' => 'UserController#postEditProfile'
])->name('submitProfile');
Related
In a Laravel/Inertia application, I try to store vinylRecords.
Therefore I created a vinylRecords resource.
Route::resource('vinylRecords', VinylRecordController::class)->only(['index', 'create','store', 'edit', 'update']);
In the frontend, the store function looks like:
methods: {
submitForm() {
this.$inertia.post(route("vinylRecords.store"), this.form, {
onSuccess: (response) => {
alert(Object.keys(response.props))
this.form.reset();
},
});
}
},
Sometimes, the routing is right and the Laravel stores the new record. But most of time, Laravel redirects to the index method without storing the data.
The store method:
public function store(StoreVinylRecordRequest $request)
{
$data = $request->validated();
$record = VinylRecord::create($data);
$record->labels()->sync($data['label_ids']);
$record->styles()->sync($data['style_ids']);
$record->specials()->sync($data['special_ids']);
return Inertia::render('vinylRecord/index', [
'records' => VinylRecordResource::collection(VinylRecord::all()),
'vinylRecordId' => $record->id
]);
}
To solve the problem, I created a new controller with a new route to store the data:
Route::post('storeVinylRecord', [StoreVinylRecordController::class, 'store'])->name('storeVinylRecord');
But the problem was the same.
How is it possible, that the routing changes from one request to the other? Is there an big error in the code from my side?
Edited: Add the StoreVinylRecordRequest
public function rules()
{
return [
'artist' => 'required|string',
'title' => 'required|string',
'barcode' => 'nullable|integer',
'genre_id' => 'nullable|integer',
'country' => 'nullable',
'year' => 'nullable|integer',
'label_ids' => 'nullable',
'style_ids' => 'nullable',
'special_ids' => 'nullable',
'thumb' => 'nullable|string',
'cover_image' => 'nullable|string',
'quantity' => 'nullable|integer',
'speed' => 'nullable|integer',
'part_type' => 'nullable|string',
'storage_location' => 'nullable|string',
'supplier_id' => 'nullable|in:suppliers,id',
'purchasing_price' => 'nullable|numeric',
'selling_price' => 'nullable|numeric',
];
}
How can I use custom error messages in a json response? I'm using Ajax to validate a login form in frontend and I've already manage how to display the Validator errors, but I can't figure out how I can retrieve a custom error message.
This is the controller:
public function LoginValid(Request $request){
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
]);
if($validator->passes()){
$user = User::where('email', $request->email)->first();
if ($user &&
Hash::check($request->password, $user->password)) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard');
}else{
return response()->json('should be any custom message here');
}
}
}else{
return response()->json(['error'=>$validator->errors()->all()]);
}
}
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: "{{ route('login-valid') }}",
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = 'dashboard';
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});
you can customize validation messages in this way. I am using your code for an example.
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
], [
'email.required' => 'email is required',
'email.string' => 'email should be valid',
'email.email' => 'email should be in proper format'
.
.
.
.
and so on
]);
above code will overwrite the laravel default messages.
I get the following error when logging in with my mobile phone:
Uncaught (in promise) Error: Request failed with status code 422
how can i fix this?
My Controller
public function login(Request $request)
{
$req = Request::create(route('passport.token'), 'POST', [
//'grant_type' => 'password',
'client_id' => 2,
'client_secret' => '326g3KM3giN4o3UHITByxPLHaZlWzqfZbWs0vWLd',
'phone_number' => $request->phone_number,
//'password' => $request->password,
]);
$response = app()->handle($req);
if ($response->status() == 400) {
return response()->json([
'message' => ''
]);
} else if ($response->status() == 401) {
return response()->json([
'message' => ''
]);
}
return $response;
I also redefined functions in the user model
public function findForPassport($identifier) {
return $this->where('phone_number', $identifier)->first();
}
public function validateForPassportPasswordGrant($password)
{
return true;
}
I've read your description. So, you have to store phone and code in the table users. To simplify it, you can store code in DB field password as an encrypted value.
$user->phone_number = $request->phone_number;
$user->password = bcrypt($code);
And then during login you can use your own code:
$req = Request::create(route('passport.token'), 'POST', [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => '326g3KM3giN4o3UHITByxPLHaZlWzqfZbWs0vWLd',
'phone_number' => $request->phone_number,
'password' => $request->code,
]);
$response = app()->handle($req);
I am getting started with lumen.
this is my web.php file
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('user', ['uses' => 'UserController#createUser']);
});
and this is my UserController.php
public function createUser(Request $request){
$this->validate($request, [
'username' => 'required',
'password' => 'required|min:3'
]);
$user = [
'username' => $request->username,
'password' => app('hash')->make($request->password),
'email' => $request->email,
'api_token' => 'asdfasd' //want should I put here
];
$user = User::create($user);
return response()->json($user, 201);
}
How do I create a new api token for that a new user who is registering?
The problem is, when i submit the form, the browser throw MethodNotAllowedHttpException in RouteCollection.php line 219:
My route
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
/* ruote for Admin */
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/profile-edit/{id}', 'Dash\\UsersController#editUser');
My controller:
public function editUser($id)
{
$auth = Auth::user()->id;
$user = User::findOrFail($id);
if($auth == $user->id){
return view('dash.users.update_profile', compact('user'));
}
return redirect('errors/404');
}
public function storeUpdatedUser($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
$user->password = bcrypt($request->password);
$user->save();
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
the view:
{!! Form::model($user, [
'method' => 'PATCH',
'url' => ['/profile-edit', $user->id],
'class' => 'form-horizontal'
]) !!}
........
WHere is the problem? And another problem is the field "password" show me a hased password, anyone can explaine me ?
You are sending a PATCH request to a get route:
Route::get('/profile-edit/{id}', 'Dash\\UsersController#editUser');
{!! Form::model($user, [
'method' => 'PATCH',
'url' => ['/profile-edit', $user->id],
'class' => 'form-horizontal'
]) !!}
Change the route from get to patch
Route::patch('/profile-edit/{id}', 'Dash\\UsersController#editUser');
Try to use Route::put('/profile-edit/{id}'...
solved:
Route::get('/profile-edit/{id}/edit', 'Dash\\UsersController#editUser');
Route::patch('/profile-edit/{id}', 'Dash\\UsersController#storeUpdatedUser');