I was read some answer in stackoverflow about this question, but I still not understand because the answer hasn't specified and make me confuse. I have some code below.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver/
My Model API
public function upload(){
$config['upload_path']='./images/';
$config['allowed_types']='jpg|png|jpeg';
$config['max_size']='2048';
$config['remove_space']=TRUE;
$config['overwrite']=TRUE;
$this->load->library('upload',$config);
if ($this->upload->do_upload('id_image')) {
$return = array(
'result'=>'success',
'file'=> $this->upload->data(),
'error'=>'');
return $return;
} else {
$return = array(
'result'=>'failed',
'file'=>'',
'error'=> $this->upload->display_errors());
return $return;
}
}
public function createMember($upload){
$data_member = [
"id_card" => $this->input->post('id_card', true),
"name" => $this->input->post('name', true),
"email" => $this->input->post('email', true),
"id_image" => $upload['file']['file_name']
];
$this->db->insert('member', $data_member);
}
My Controller API
public function index_post(){
$upload = $this->Member_model_api->upload();
if ($this->Member_model_api->createMember($upload) > 0) {
$this->response([
'status' => true,
'message' => 'Member Data was Added'
], REST_Controller::HTTP_CREATED);
} else {
...
REST_Controller::HTTP_BAD_REQUEST);
}
}
Output from Postman
Message: Call to undefined method Member_model_api::upload()
Filename: C:\xampp\htdocs\org\application\controllers\api_controller\Org_member.php
I hope the other developers give me some reference like my code above, thank you very much.
Related
I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem
This is my controller function to store a product, i have the error in the $validator, i'm using this in the api route, i have the error of the title, i've try so many things and nothing works, please helpme, if i send in $validator the $req->all() it works, but i need to send a picture and thats why i'm using the $productReq, i'm using laravel 8
public function store(Request $req)
{
$productReq = new Product($req->all());
if ($req->file('file') == null) {
$req->file = "";
} else {
$image = $req->file('file')->store('public/images');
$url = Storage::url($image);
$productReq->file = $url;
}
$rules = array(
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
);
$validator = Validator::make($productReq, $rules);
if ($validator->fails()) {
return response()->json([
'error' => true,
'response' => $validator->errors()
], 401);
} else {
$product = Product::create($productReq);
return response()->json([
'error' => false,
'response' => $product,
], 200);
}
}
Validator::make() expects an array of data to be provided to it. You've provided an instance of a Product, which Laravel doesn't know what to do with. What you want to do is validate your data before creating an instance of Product.
public function store(Request $req)
{
$rules = array(
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
);
$validator = Validator::make($req->input(), $rules);
if ($validator->fails()) {
return response()->json([
'error' => true,
'response' => $validator->errors()
], 401);
}
$product = new Product($req->input());
if ($req->file('file') == null) {
$req->file = "";
} else {
$image = $req->file('file')->store('public/images');
$url = Storage::url($image);
$product->file = $url;
}
$product->save();
return response()->json([
'error' => false,
'response' => $product,
], 200);
}
You can also simplify the controller's logic by making use of some of Laravel's conveniences. However, it may produce responses that do not match what the front end expects (i.e. JSON message when a validation error is encountered).
public function store(Request $req)
{
// Laravel's `validate()` method on a Request will validate against the
// current request data and return the valid input. It will throw an Exception
// if validation fails, which Laravel will handle and reply with the validation errors.
$validatedInput = $req->validate([
'name' => 'required',
'price' => 'required',
'file' => 'required|image'
])
$product = new Product($validatedInput);
// ... file logic
$product->save();
// In Laravel, you can return an array from a controller. Laravel
// will assume it's supposed to be JSON, and encode it automatically for you
return [
'error' => false,
'response' => $product,
];
}
I'm just learning CI4 from Youtube "web programming unpas" on episode 9 insert data (its using indonesia language). Well I followed the course and tried to insert data. After insert data to database, it will be redirected to the index file.
So the error is showing localhost send an invalid response
Idk what's the problem
Here is the code
routes.php
$routes->get('/', 'pages::index');
$routes->get('/komik/create', 'komik::create');
$routes->get('/komik/(:segment)', 'komik::detail/$1');
controller/komik.php
<?php
namespace App\Controllers;
use App\Models\komikmodel;
class komik extends BaseController
{
protected $komikmodel;
public function __construct()
{
$this->komikmodel = new komikmodel();
}
public function index()
{
$data = [
'title' => 'Daftar Komik' ,
'komik' => $this->komikmodel->getkomik()
];
return view('komik/index', $data);
}
public function detail($slug)
{
$data = [
'title' => 'Detail Komik',
'komik' => $this->komikmodel->getkomik($slug)
];
if(empty($data['komik']))
{
throw new \CodeIgniter\Exceptions\PageNotFoundException('Judul Komik '. $slug. 'Tidak Ditemukan');
}
return view('komik/detail', $data);
}
public function create()
{
$data = [
'title' => 'Form Tambah Data Komik'
];
return view('/komik/create', $data);
}
public function save()
{
$slug = url_title($this->request->getVar('judul'), '-', true);
$this->komikmodel->save([
'judul' => $this->request->getVar('judul'),
'slug' => $slug,
'penulis' => $this->request->getVar('penulis'),
'penerbit' => $this->request->getVar('penerbit'),
'sampul' => $this->request->getVar('sampul')
]);
session()->setFlashData('pesan', 'Data berhasil di tambahkan!');
return redirect()->to('/komik');
}
}
Any advice will be appreciated
I'm working with codeigniter REST API. In my API call i'm trying to get value from $this->input->get('id') but does not get any value from the get.
public function data_get($id_param = NULL){
$id = $this->input->get('id');
if($id===NULL){
$id = $id_param;
}
if ($id === NULL)
{
$data = $this->Make_model->read($id);
if ($data)
{
$this->response($data, REST_Controller::HTTP_OK);
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No record found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
$data = $this->Make_model->read($id);
if ($data)
{
$this->set_response($data, REST_Controller::HTTP_OK);
}
else
{
$this->set_response([
'status' => FALSE,
'error' => 'Record could not be found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
In the above code $id doesn't return any value.
Hope this will help you :
Use either $this->input->get('id') or $this->get('id') both should work
Your data_get method should be like this :
public function data_get($id_param = NULL)
{
$id = ! empty($id_param) ? $id_param : $this->input->get('id');
/*
u can also use this
$id = ! empty($id_param) ? $id_param : $this->get('id');
*/
if ($id)
{
$data = $this->Make_model->read($id);
if ($data)
{
$this->response($data, REST_Controller::HTTP_OK);
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No record found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No id is found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
Please change your code from $id = $this->input->get('id'); to $id = $this->get('id');
This should solve your problem.
I can't seem to figure out how I unit test the update of my controller. i'm getting the following error:
method update() from Mockery_0_App.... Should be called exactly 1 times but called 0 times.
After I remove the if statement in the update (after checking if the allergy exists), I get the following error on the line where I add the id the the unique validation rule:
Trying to get property of on object
My Code:
Controller:
class AllergyController extends \App\Controllers\BaseController
{
public function __construct(IAllergyRepository $allergy){
$this->allergy = $allergy;
}
...other methods (index,show,destroy) ...
public function update($id)
{
$allergy = $this->allergy->find($id);
//if ($allergy != null) {
//define validation rules
$rules = array(
'name' => Config::get('Patient::validation.allergy.edit.name') . $allergy->name
);
//execute validation rules
$validator = Validator::make(Input::all(), $rules);
$validator->setAttributeNames(Config::get('Patient::validation.allergy.messages'));
if ($validator->fails()) {
return Response::json(array('status' => false, 'data' => $validator->messages()));
} else {
$allergy = $this->allergy->update($allergy, Input::all());
if ($allergy) {
return Response::json(array('status' => true, 'data' => $allergy));
} else {
$messages = new \Illuminate\Support\MessageBag;
$messages->add('error', 'Create failed! Please contact the site administrator or try again!');
return Response::json(array('status' => false, 'data' => $messages));
}
}
//}
$messages = new \Illuminate\Support\MessageBag;
$messages->add('error', 'Cannot update the allergy!');
return Response::json(array('status' => false, 'data' => $messages));
}
}
TestCase:
class AllergyControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->allergy = $this->mock('App\Modules\Patient\Repositories\IAllergyRepository');
}
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
public function testIndex()
{
$this->allergy->shouldReceive('all')->once();
$this->call('GET', 'api/allergy');
$this->assertResponseOk();
}
...Other tests for Index and Show ...
public function testUpdate()
{
$validator = Mockery::mock('stdClass');
Validator::swap($validator);
$input = array('name' => 'bar');
$this->allergy->shouldReceive('find')->with(1)->once();
$validator->shouldReceive('make')->once()->andReturn($validator);
$validator->shouldReceive('setAttributeNames')->once();
$validator->shouldReceive('fails')->once()->andReturn(false);;
$this->allergy->shouldReceive('update')->once();
$this->call('PUT', 'api/allergy/1', $input);
$this->assertResponseOk();
}
}
Config validation rules file:
return array(
'allergy' => array(
'add' => array(
'name' => 'required|unique:Allergy'
),
'edit' => array(
'name' => 'required|unique:Allergy,name,'
),
'messages' => array(
'name' => 'Name'
)
)
);
Is there a way to actually mock the value provided into the validation rule? Or what is the best way to solve this?
I changed my code to this and now it works! :)
$validator = Mockery::mock('stdClass');
Validator::swap($validator);
$allergyObj = Mockery::mock('stdClass');
$allergyObj->name = 1;
$input = array('name' => 'bar');
$this->allergyRepo->shouldReceive('find')->with(1)->once()->andReturn($allergyObj);
$validator->shouldReceive('make')->once()->andReturn($validator);
$validator->shouldReceive('setAttributeNames')->once();
$validator->shouldReceive('fails')->once()->andReturn(false);;
$this->allergyRepo->shouldReceive('update')->once();
$this->call('PUT', 'api/allergy/1', $input);
$this->assertResponseOk();