When I clicked add button, MethodNotAllowedHttpException is appeared - laravel

When I clicked on the add button, a MethodNotAllowedHttpException error appeared. What is wrong in my code?
I have read all of the version of correction but nothing helped me.
This is my getdata() function inside AjaxdataController:
function getdata()
{
$users=User::select('id','name','lastname','email','created_at');
return DataTables::of($users)
->addColumn('action', function ($user) {
return '<i class="glyphicon glyphicon-edit"></i> Edit';
})
->make(true);
}
function postdata (Request $request)
{
$validation=Validator::make($request-> all(),[
'name' =>'required',
'lastname' => 'required',
'email' =>'required',
'password' =>'required'
]);
$error_array= array();
$success_output='';
if ($validation->fails())
{
foreach ($validation->messages()->getMessages as $field_name => $messages) {
$error_array[]=$messages;
}
}
else
{
if ($request->get('button_action')=="insert")
{
$user =new User([
'name' =>$request->get('name'),
'lastname'=>$request->get('lastname'),
'email'=>$request->get('email'),
'password'=>$request->get('password')
]);
$user->save();
$success_output= '<div class="alert alert-success"> Data Inserted </div>';
}
}
$output=array(
'error' =>$error_array,
'success'=>$success_output
);
echo json_encode($output);
}

I assume that you defined the route as a GET request but the form is probably sending a POST request. Change your route definition.
// Change this
Route::get('/foo', 'FooController#bar')
// To this
Route::post('/foo', 'FooController#bar')

Related

Laravel - How to pass parameter from controller to route and use it in another controller?

I have configured a resource route as below
Route::resource('users', UserController::class);
When a user posts data, it will call the store method in the controller where it will add the data and set a message for success/failure.
public function store(Request $request)
{
// return $request;
$request->validate(
[
"firstName" => 'required',
"lastName" => 'required',
"phoneNo" => 'required',
"email" => 'email:rfc,dns'
]
);
$date = date(now());
$data = [
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'phoneNo' => $request->phoneNo,
'email' => $request->email,
'designation' => $request->designation,
'status' => $request->status,
'createdAt' => $date,
'updatedAt' => $date,
];
$user = Firebase::insertData($data, static::$collection);
if ($user->id() != null) {
$message = "User Created Successfully";
} else {
$message = "Something went wrong. Please contact System Admin with error code USR001";
}
return redirect()->route('users.index', ['message' => $message]);
}
This will redirect to the index method of the same controller. How can I use the $message parameter in the index method and send it to the view? My index method is below
public function index()
{
$userCollection = app('firebase.firestore')->database()->collection('users');
$userData = $userCollection->documents();
$response = [];
$app = app();
foreach ($userData as $data) {
$user = $app->make('stdClass');
$user->firstName = $data["firstName"];
$user->lastName = $data["lastName"];
$user->phoneNo = $data["phoneNo"];
$user->email = $data["email"];
$user->designation = $data["designation"];
$user->status = $data["status"];
$user->createdAt = $data["createdAt"];
$user->updatedAt = $data["updatedAt"];
array_push($response, $user);
}
return view('pages.user.list-user', ['response' => $response]);
}
You can directly pass the message as a flash message using the with() method with the redirect method.
Edit your redirect code as:
return redirect()->route('users.index')->with('message', $message]);
and add the below code in your pages.user.list-user blade file:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
Visit https://laravel.com/docs/8.x/redirects#redirecting-with-flashed-session-data for more info on redirects with a flash message.
Replace your redirect code :
return redirect()->route('users.index', ['message' => $message]);
with
return view('pages.user.list-user', ['message' => $message]);
(1) First of all, pass the message in the parameter of index function:
public function index($message)
{
...
}
(2) This is okay, you wrote correctly:
return redirect()->route('users.index', ['message' => $message]);
(3) Now just access the message in the view (blade) and print it:
{{ $message }}
You can also store message in $response array and simply pass the $response to the desired view:
$response['message'] = $message;
You can have the index method like if the parameter used in the controller.
public function index(Request $request)
{
// Your code
$message = $request['message'];
}
If you want to access the message in view use
return redirect()->route('users.index')->with('message', $message]);
and access from the view using session('message') like in OMi Shah's answer

How to display array data after store & email sent?

UPDATE
I have contact form. it works good. I would like to display $data array at
final page which is admintemp.blade.php.
I can display $data array at one step before final page. but I would like to display those at last page too.
I thoguht just add this
return view('mail.complete', ['data' => $data]);
is fine. but I got this error
Invalid argument supplied for foreach()
Could you teach me right way please?
Here is my code
/*
*confirm page
*/
public function confirm(Request $request)
{
$rules = [
'orderer' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
$data = session()->regenerateToken();
return view('mail.complete', ['data' => $data]);
}
UPDATES 2
complete.blade.php
#foreach ($data as $val)
{{ $val->id }}
{{ $val->tel }}
#endforeach
for example you have two step form
first step post method:
public function postCreateStep1(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
return redirect('/create-step2');
}
second step post method:
public function postCreateStep2(Request $request)
{
$validatedData = $request->validate([
'family' => 'required',
]);
if (empty($request->session()->get('contact'))) {
$contact = new Contact();
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
} else {
$contact = $request->session()->get('contact');
$contact->fill($validatedData);
$request->session()->put('contact', $contact);
}
$created_contact = Contact::create([
'name' => $contact->name,
'family' => $contact->family,
]);
// Do whatever you want with $created_contact
return redirect('/');
}

How can i update my form with validation in laravel?

My form validation is not working in Laravel. How can I update my form with validation in Laravel?
You can check my code here-
public function update(Request $request, $id)
{
$id->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
return redirect('/info');
}
You need to call validate on $request, like this-
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
Here is the full code-
public function update(Request $request, $id)
{
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
if (!$validator->fails()) {
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
} else {
\Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
return redirect('/info');
}
I have added one more condition in the code to handle the validation errors. If validation fails then it will redirect back with your inputs as well as the validation error messages. Make sure you have error session flash in your blade views to show the errors.
For me this is best way , i can keep on track on query and other exceptions by putting it in try catch block
public function update(Request $request, $id)
{
try{
$validator = Validator::make($request->all(), [
'name' => 'required',
'UserName' => 'required',
'Password' => 'required',
'email' => 'required|email',
]);
if($validator->fails()) {
return redirect()
->route('path_to_edit_form')
->withErrors($validator)
->withInput();
}
Info::where('id',$id)->update([
'user_id' => $request->get('user_id'),
'Name' => $request->get('Name'),
'UserName' => $request->get('UserName'),
'Password' => $request->get('Password'),
]);
return back()->with([
'alert_type' => 'success',
'message' => 'User info updated successfully.'
]);
}catch(\Exception $e){
return back()->with([
'alert_type' => 'danger',
'message' => $e->getMessage()
]);
}
}

return redirect() is not working after a failed validation

I have a form where users can edit a branch's info, once the user submits that form, the update() method checks for the validity of the submitted data such as the description must be unique to every subscriber. While the validation WORKS, it doesn't redirect to the exact url/page that I want if the validation fails. It stays in the same edit form.
here's the code of my update() method:
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$this->validate($request, [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
], $messages);
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Note: the url of the edit form is /branch/edit/{id} while the page I want to redirect after submission is /branches.
Is my validation wrong? Did I miss something?
Thanks! :)
According to the laravel docs you can redirect to a different route by using the Validator facade
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$validator = Validator::make($request->all(), [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
],
$messages);
if ($validator->fails()) {
return redirect('/branches')
->withErrors($validator)
->withInput();
}
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Make sure you use the Validator facade at the beginning of your controller file use Validator;

laravel 5.2 - check if field is empty or not

I want to check if some field is empty or not. If is empty, the user can update the profile without change the current password.
If is not empty, store new value of password. My controller is:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
$new_password = false;
if($new_password != ""){
$new_password = bcrypt($request->new_password);
$user->password = $new_password;
}
$user->save();
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
but dont work, no password change if I put some value
image explain better
Try this:
public function storeUpdatedUser(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail(Auth::user()->id);
$user->update($request->all());
if(!empty($request->input('new_password'))) {
$new_password = bcrypt($request->input('new_password'));
$user->password = $new_password;
$user->save();
}
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
Laravel Check Request Input Exists
if($request->has('new_password ')) {
dd('new_password is exists.');
} else {
dd('new_password is not exists.');
}
Laravel Check Request Input Field Empty or not
if($request->filled('new_password ')) {
dd('new_password is not empty.');
} else {
dd('new_password is empty.');
}
Laravel Check Request Input Field Empty or not
if(!empty($request->input('new_password '))) {
dd('new_password is not empty.');
} else {
dd('new_password is empty.');
}
This is what works for me in Laravel 5.7:
$user = Auth::user();
$user->update($request->filled('password') ? $request->all() : $request->except(['password']));

Resources