I need to fetch user_id, firstname, lastname from user table and feedback_id,comment,user_id and recipe_id from feedback table where user_id from user is equal to the user_id in user table.
Review.html
<div class="items item item-avatar" ng-repeat="comment in feedbackdata">
<img src="img/asd.jpg">
<h2>{{comment.firstname}} {{comment.lastname}}</h2>// I don't know what to put here
<p>{{comment.feedback_id}}</p>
<p>{{comment.comment}}</p>
<p>{{comment.user_id}}</p>
<p>{{comment.recipe_id}}</p>
Controller.js
.controller('CommentCtrl', function($scope, CommentList,$state,$location,SessionService,getFeedbackService) {
$scope.userdata = SessionService.getObject('userdata');
$scope.newComment={};
$scope.newComment.userID = $scope.userdata.user_id;
getFeedbackService.all().then(function(payload) {
$scope.feedbackdata = payload.data;
console.log(payload);
});
$scope.addComment = function(){
CommentList.add($scope.newComment);
console.log($scope.newComment);
};
})
Service.js
.factory('getFeedbackService', function($http){
return {
all: function() {
return $http.get("http://localhost/admin-recipick/api/Main/get_feedback_data");
}
};
});
main.php
public function get_feedback_data()
{
$postdata = json_decode(file_get_contents("php://input"));
$feedback = $this->User_model->feedback_data();
echo json_encode($feedback);
}
user_model.php
public function feedback_data()
{
$this->db->select('*');
$this->db->from('feedback')
$this->db->join('user','user.user_id = feedback.user_id');
$query = $this->db->get();
return $query->result_array();
}
Related
I'm working on a Vue.js/Laravel web application for a company that offers school workshops. I've managed to make it possible to add an image to a workshop when it doesn't yet have one (POST), but when I try to update an existing workshop picture (PUT), $request->file always returns null and I can't seem to figure out why.
Workshops table:
Uploads table:
(workshop_picture contains the id of the corresponding upload in the uploads table)
onFileSelected function in the workshop edit page:
onFileSelected (event) {
this.selectedFile = event.target.files[0]
let formData = new FormData()
formData.append('file', event.target.files[0])
if (this.workshop.workshop_picture) {
console.log('Workshop already has a picture, updating current picture...')
axios.put('/api/upload/' + this.workshop.workshop_picture.id,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
this.workshop.workshop_picture = response.data.id
this.workshop_picture_preview = '/uploads/' + response.data.internal_name
})
.catch(function () {
alert('Uploaden mislukt!')
})
}
}
UploadController.php:
class UploadController extends Controller
{
public function store(Request $request)
{
$request->validate(['file' => 'mimes:jpeg,png,jpg']);
$internal_name = Str::random(32) . '.' . $request->file->extension();
$upload = new Upload();
$upload->name = $request->file->getClientOriginalName();
$upload->internal_name = $internal_name;
$upload->size = $request->file->getSize();
$upload->save();
$request->file->move(public_path('uploads'), $internal_name);
return response($upload, 200)->header('Content-Type', 'json');
}
public function update(Request $request, $id)
{
$request->validate(['file' => 'mimes:jpeg,png,jpg']);
$internal_name = Str::random(32) . '.' . $request->file->extension();
$upload = Upload::find($id);
$upload->name = $request->file->getClientOriginalName();
$upload->internal_name = $internal_name;
$upload->size = $request->file->getSize();
$upload->save();
$request->file->move(public_path('uploads'), $internal_name);
return response($upload, 200)->header('Content-Type', 'json');
}
}
The form data clearly contains the selected file, so I have absolutely no clue why it says $request->file is null.
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.
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);}});});
});
I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>
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. :)