POST 500 (Internal Server Error) - Laravel and Ajax - php

I want to send post request with ajax to controller in laravel. The ajax request send two input arguments and I want controller to find the column in the database with the first argument and then to set the name attribute with the second input argument. But I have this error message Creating default object from empty value
Ajax function:
$('#saveUserProfile').on('click', function () {
var $finduser = $('input[name=findUser]').val();
var $name = $('input[name=userprofilename]').val();
$.ajax({
type:"POST",
url:'/code/task1/public/updateUser',
data: {
'name' : $name,
'finduser' : $finduser,
// 'email' : $email,
},
success:function(data){
$("#input1").val(data[0].name);
}
});
});
and the function in my controller
public function updateUser(Request $request){
$return_array = array();
$findUserInput = $request->get('finduser');
$user = User::where('name',$findUserInput) -> first();
$user->name = $request->get('name');
$user->save();
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Update: I also make ajax function and controller for finding user which is working good.
ajax function:
$('#buttonFindUser').on('click', function () {
var $name = $('input[name=findUser]').val();
$.ajax({
type:"GET",
url:'/code/task1/public/findUser',
data: {
'name' : $name,
},
success:function(data){
$("#input1").val(data[0].name);
$("#input2").val(data[0].email);
$("#input3").val(data[0].created_at);
}
});
});
Function in my controller:
public function findUser(Request $request){
$return_array = array();
$findUserInput = $request->get('name');
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Any ideas?

But I have this error message Creating default object from empty value
What's happening is that you are trying to save a user that doesn't exist. You need to check if the $user is null or not in your controller. Right now, the user couldn't be found with the provided name so $user becomes null.
So, you can modify your code to do a null check on $user like so:
public function updateUser(Request $request){
$return_array = array();
$findUserInput = $request->get('finduser');
$user = User::where('name',$findUserInput) -> first();
if(!$user)
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
$user->name = $request->get('name');
$user->save();
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Here's the null check:
if(!$user)
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
When we don't have a valid user, we just reply back with a json response stating that it couldn't be found.
Update:
Seeing as your input is not being retrieved in the controller, you need to make some changes in JS:
First, you are doing a post request and I cannot see a CSRF token. To add it, follow this answer: https://stackoverflow.com/a/37582060/6270112
So, your data will now become:
data: '_token=' + $('#token').val() + '&name=' + $name + '&finduser=' + $finduser
Also, as aleksejjj mentioned, you need to fix your jquery selectors as well. So, your existing selectors:
var $finduser = $('input[name=findUser]').val();
var $name = $('input[name=userprofilename]').val();
will become:
var $finduser = $('input[name^="findUser"]').val();
var $name = $('input[name^="userprofilename"]').val();
Next, in your controller you need to replace $request->get(...) with $request->input(...).
$findUserInput = $request->get('finduser');
will become
$findUserInput = $request->input('finduser');
and repeat the same with the name field as well.

You need to check your user exist
$user = User::where('name', $findUserInput)->first();
if($user)
{
$user->name = $request->get('name');
$user->save();
}

change this code
$user = User::where('name',$findUserInput) -> first();
to
$user = User::where('name','=',$findUserInput) -> first();
I hope this will work. :)

Related

View /Fetch logged user data when logged in - CodeIgniter

My problem is my data are being fetched at once, all of them. I need to view each user's data when Im on different logged in user. For example: For user1 I need to have Product1 and user2 I need to have Product2 but right now all Im getting is I can fetch all user's data.
here is my Model
As you can see I added my join query but still fetching all my data
public function showAllReviewers(){
$this->db->join('teachers', 'teachers.id = reviewers.user_id');
$query = $this->db->get('reviewers');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
My Controller
public function showAllReviewers()
{
$result = $this->reviewer_model->showAllReviewers();
echo json_encode($result);
}
My View
<tbody id="showdata">
</tbody>
I'm using ajax/js to fetch my data so here is my ajax/js script for additional info
//function
function showAllReviewers(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>reviewers/showAllReviewers',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr class="table-info">'+
'<td>'+data[i].subject+'</td>'+
'<td>'+data[i].category+'</td>'+
'<td>'+data[i].set_rev+'</td>'+
'<td>'+data[i].group_name+'</td>'+
'<td>'+
' <span class="iconify" data-icon="bx:bx-edit" data-inline="false"></span> '+
' <span class="iconify" data-icon="bx:bx-trash" data-inline="false"></span> '+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
EDIT: Login Controller
// Log in teacher
public function login(){
$this->form_validation->set_rules('code', 'Code', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('teachers/login');
$this->load->view('templates/footer');
} else {
// Get code
$code = $this->input->post('code');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user = $this->teacher_model->login($code, $password);
if($user){
// Create session
$user_data = array(
'user_id' => $user->id,
'name' => $user->name,
'code' => $code,
'logged_in' => true
);
$this->session->set_userdata($user_data);
redirect('teacher/home');
} else {
redirect('teachers/login');
}
}
}
Well, you can store user data like id etc in session when user logs in, like below in your controller:
$this->session->set_userdata('user_details', $user_data); // say user_details is the key we store it in
In your model, you can do like below:
<?php
public function showAllReviewers(){
$this->db->join('teachers', 'teachers.id = reviewers.user_id');
$this->db->where('reviewers.user_id',$this->session->userdata('user_details')['user_id']);
$query = $this->db->get('reviewers');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
Or an even better approach is to have a private variable say user_id and set the value in the constructor. This would make sure that whenever you are accessing model instance in your controller, you already have it in your model instead of retrieving from session always.
<?php
class YourModel extends CI_Model{
private $user_id;
function __construct(){
$this->user_id = $this->session->userdata('user_details')['user_id'];
}
public function showAllReviewers(){
$this->db->join('teachers', 'teachers.id = reviewers.user_id');
$this->db->where('reviewers.user_id',$this->user_id);
$query = $this->db->get('reviewers');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
}
You must add a where condition in showAllReviewers() function's Sql query by passing current logged in User/Teacher Id Or in case of CI you can fetch the same using isLogged/getId function which used to be present in system/library/customer.

Record not updating through AJAX request in Laravel

I am using jquery ajax in laravel for update data from database. I wrote this code and the $ajax() part not working. but everything before that working great. Please let me know where I am doing wrong?
1) AJAX function:
$(".Editform").click(function() {var id=$(this).attr("id");
// alert(id);
$("#saveBtn").on ('click',function() { var name =
// alert(name);
$("input[name=name]").val();
$.ajax({type:'POST',url:'edit-records',data:{id:id,name:name },success:
function(result){alert.show(); $('#MyModal').modal('hide');
console.log(result);}});});});
2) Controller:
public function updaterec(Request $request, $id)
{
$name = $request->input('name');
DB::update('update m_employee set employee_name = ? where employee_id = ?',[$name,$id]);
echo "Record updated successfully";
}
3) web.php:
Route::post('edit-records','viewemployeeController#updaterec');
Route::get('view-records','viewemployeeController#index');
You should not use $id as parameter if it's not defined in the route.
Change your controller:
public function updaterec(Request $request)
{
$name = $request->input('name');
$id = $request->input('id');
DB::update('update m_employee set employee_name = ? where employee_id = ?',[$name,$id]);
echo "Record updated successfully";
}
---------OR---------
Change your Route and Ajax code:
Route::post('edit-records/{id}','viewemployeeController#updaterec');
$.ajax({type:'POST',url:'edit-records/'+id,data:{id:id,name:name },success: function(result){alert.show(); $('#MyModal').modal('hide'); console.log(result);}});});
});

Laravel CustomRequest authorize, pass request data to validate the auth user customer id and the model id match

I'm trying to fix an if-else statement in the request for my controller. What I'm trying to do is: if the auth::user-companyID == $request-companyID then true else false; The companyID for the request is in a hidden field on the blade file.
CustomRequest
public function authorize()
{
$user = Auth::user();
if ($user->companyID == $request->companyID) {
return true;
} else {
return false;
}
}
Controller
public function edit(EquipmentRequest $request, $id)
{
$validated = $request->validated();
$user = Auth::user();
$equipment = EquipmentModel::where('id', '=', $id)->first();
$equipment->Year = $request->Year;
$equipment->Make = $request->Make;
$equipment->Model = $request->Model;
$equipment->Type = $request->Type;
$equipment->unitNumber = $request->unitNumber;
$equipment->AnnualInspectionDate = $request->AnnualInspectionDate;
$equipment->userID = $request->userID;
$equipment->companyID = $user->companyID;
$e = $equipment->save();
if ($e) {
$request->session()->flash('success', 'The equipment was successfully updated.');
} else {
$request->session()->flash('error',
'An error occurred while saving. Please refresh your browser and try again.');
}
return redirect()->route('equipmentlist');
}
This form worked before I started messing with it so I know the form is working correctly on the blade file. I'm not sure if you can pass the request data the way I'm doing it or if I have to do a construct to do it this way. I would really appreciate any advice.
use Illuminate\Http\Request;
public function authorize()
{
$user = auth()->user();
return $user->companyID === request()->companyID;
}

Laravel save multi part form

I have a 3 part form that I want to be able to update the database after each submit. There is one table that holds all the fields below.
form1 asks for first and last name
form2 asks for email and phone
form3 asks for city and state
In my controller I have 3 separate functions to save each step of the form:
public function name(Request $request){
$lead = Lead::firstOrNew(123);
$lead->firstName = $request->get('firstName ');
$lead->lastName = $request->get('lastName');
$lead->save();
return redirect('/form2');
}
public function info(Request $request){
$lead = Lead::find(123);
$lead->email = $request->get('email');
$lead->phone = $request->get('phone');
$lead->save();
return redirect('/form3');
}
public function address(Request $request){
$lead = Lead::find(123);
$lead->city = $request->get('city');
$lead->state = $request->get('state');
$lead->save();
return redirect('/done');
}
Is there any way to combine that to one update function?
Just do conditional check, update the model and define redirect url:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
if ($request->has('firstName') && $request->has('lastName')) {
$lead->firstName = $request->get('firstName ');
$lead->lastName = $request->get('lastName');
$redirect = '/form2';
} else if ($request->has('email') && $request->has('phone')) {
$lead->email = $request->get('email');
$lead->phone = $request->get('lastName');
$redirect = '/form3';
} else if ($request->has('city') && $request->has('state')) {
$lead->city = $request->get('city');
$lead->state = $request->get('state');
$redirect = '/done';
}
$lead->save();
return redirect($redirect);
}
Also, you can probably do group update via update just make sure you whitelist the attributes in your model
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
if ($request->has('firstName') && $request->has('lastName')) {
$redirect = '/form2';
} else if ($request->has('email') && $request->has('phone')) {
$redirect = '/form3';
} else if ($request->has('city') && $request->has('state')) {
$redirect = '/done';
}
return redirect($redirect);
}
Or I'd better just add a redirect variable to your form like:
<input type="hidden" name="redirect" value="form1">
and simplify your controller method like:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
return redirect($request->input('redirect'));
}
You could refactor the methods to call a common "update" function. See example code below.
public function name(Request $request){
$this->update(123, $request);
return redirect('/form2');
}
public function info(Request $request){
$this->update(123, $request);
return redirect('/form3');
}
public function address(Request $request){
$this->update(123, $request);
return redirect('/done');
}
private function update($id, $request) {
$lead = Lead::find($id);
foreach ($field as ['firstName', 'lastName', ...]) {
if ($request->has($field)) {
$lead->{$field} = $request->get($field);
}
}
$lead->save();
}
You can add a hidden field to all three forms (but with the name name, e.g form_name), and set their values to identify the form (form1, form2, form3) when it is submitted. Then in your controller, you check the value of the form_name field on the request to determine where you want to redirect to, like this:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
//this will be from the hidden field (form_name)
$form_type = $request->get('form_name');
if ($form_type == 'form1') {
$redirect = '/form2';
} else if ($form_type == 'form2') {
$redirect = '/form3';
} else if ($form_type == 'form3') {
$redirect = '/done';
}
return redirect($redirect);
}
If you have the option for using javaScript then save the first and second form data on cookies or local storage and when the user reaches last part of the form then take data out of cookies or local storage then added with the last form, but keep these in the hidden input.
Given that HTTP requests are stateless (which means each request know nothing about the one before and after it), I would rather prefer you use sessions, so that you can be able to store information as you redirect from one form to the other. In that case, your code should look like so:
<?php
public function name(Request $request){
Session::put('nameData', $request->all()); //Store the info from form1 in session and redirect to form2
return redirect('/form2');
}
public function info(Request $request){
$validSessionData = Session::has('nameData');
if (!$validSessionData) { //Check if the user filled form1, if not, go back to form1
return redirect('/form1');
}
$nameAndInfo = Session::pull('nameData', []) + $request->all(); //Merge the info from form1 with info from form2. You could decide to keep them separate and merge later.
Session::put('nameAndInfo', $nameAndInfo);
return redirect('/form3');
}
public function address(Request $request){
$validSessionData = Session::has('nameAndInfo');
if (!$validSessionData) { Another check. You could also extend this by checking for form2 session data
return redirect('/form1');
}
$allData = Session::pull('nameAndInfo', []) + $request->all(); //Merge all session data
$lead = Lead::firstOrNew(123);
$lead->firstName = $allData['firstName'];
$lead->lastName = $allData['lastName'];
$lead->email = $allData['email'];
$lead->phone = $allData['phone'];
$lead->city = $allData['city'];
$lead->state = $allData['state'];
$lead->save();
return redirect('/done');
}

Laravel change database data in filter.php

I want to change database data before and after App function in filter.php file.
I try to do like in that tutorial:
http://alex.leonard.ie/2013/08/02/laravel-tracking-last-activity-date-of-authorised-user/
App::before(function($request)
{
$user = Auth::user();
$user->online = 1;
$user->save();
});
But i get error: ErrorException (E_UNKNOWN) Creating default object from empty value
Mybe someone can help?
App::before(function($request)
{
if (Auth::check()){
$user = Auth::user();
$user->online = 1;
$user->save();
}
});
Note that this will only work if the user is logged in.
Try this.
App::before(function($request){
if(Auth::check()){
$user = Auth::user();
$user->online = 1;
$user->save();
}
});

Categories