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
Related
i have a problem when i use API Resources inside another API Resources class like this:
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
but when I remove the class the problem disappears like this :
if (! Route::is('job.*')) {
$data['sites']= $this->sites;
$data['jobs'] = $this->jobs;
}
this is -> image for error
this is my code :
class CustomerResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'billing_details' => $this->billing_details,
'billing_info' => [
'address' => $this->billing->address,
'street_num' =>$this->billing->street_num,
'country' =>$this->billing->country->name,
'city' =>$this->billing->city,
'postal_code' =>$this->billing->postal_code,
'credit_limit' =>$this->billing->credit_limit,
'payment_term_id' =>$this->billing->payment_term_id,
'send_statement' =>$this->billing->send_statement
],
'contacts' => $this->contacts,
'sitecontact' => $this->sitecontact,
];
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
return $data;
}
}
I called CustomerRessource class on JobRessource class which leads to an infinite loop between them
JobRessource class
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
I fixed it by using this condition on JobRessource
if (Route::is('job.*')) {
$data['customer' ] = new CustomerResource($this->customer);
}
JobRessource with condition
#N69S thank you for your comment
Adding content from Laravel to Firebase database as follows:
$postRef = $this->database->getReference($this->tablename)->push($postData);
But I don't know how to add content from Laravel to Firestore. This is my Firestore:
This is how Laravel looks like:
These are my codes:
<?php
namespace App\Http\Controllers\Firebase;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Kreait\Firebase\Contract\Firestore;
class ContactController extends Controller
{
public function __construct(Firestore $firestore)
{
$this->firestore = $firestore;
$this->tablename = 'kategoriler';
}
public function index()
{
return view('firebase.contact.index');
}
public function create()
{
return view('firebase.contact.create');
}
public function store(Request $request)
{
$postData = [
'comment' => $request->comment,
'iD' => $request->iD,
'imgUrl' => $request->imgUrl,
'lat' => $request->lat,
'location' => $request->location,
'lon' => $request->lon,
'name' => $request->name,
'youtubeId' => $request->youtubeId,
];
$postRef = $this->app('firebase.firestore')->database()->collection($this->tablename)->Document(0)->collection('bolgeler')->push($postData);
if($postRef)
{
return redirect('contacts')->with('durum','İçerik eklendi.');
}
else
{
return redirect('contacts')->with('durum','İçerik eklenemedi.');
}
If you want add data to bolgeler collection with auto document name, you can do this :
$postRef = $this->app('firebase.firestore')->database()->collection('bolgeler')->newDocument()->set($postData);
or :
$posref = $this->firestore->database()->collection('bolgeler')->newDocument()->set($postData);
when you nedd add specific name :
$postRef = $this->app('firebase.firestore')->database()->collection('bolgeler')->document('id001')->set($postData);
or:
$posref = $this->firestore->database()->collection('bolgeler')->document('id001)->set($postData);
In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Here i am getting inserted data to database but how to write this in foreach loop to get multiple data please help me as a fresher am totally confused..
My controller
class Student extends CI_Controller {
public function _construct()
{
parent::_construct();
//call model
$this->load->model("StudentModel","m");
}
function index()
{
$this->load->view("index");
}
function savedata()
{
//create array for get data from index
//$data=array(
// 'studentname' => $this->input->post('studentname'),
//'gender' => $this->input->post('gender'),
//'phone' => $this->input->post('phone')
// );
$data = array(
array(
'studentname' => 'Reddy' ,
'gender' => 'Male' ,
'phone' => '456879'
),
array(
'studentname' => 'Yalla' ,
'gender' => 'Female' ,
'phone' => '12345678'
)
);
//mean that insert into database table name tblstudent
$this->db->insert_batch('tblstudent',$data);
//mean that when insert already it will go to page index
redirect("Student/index");
}
function edit($id)
{
$row=$this->m->getonerow($id);
$data['r']=$row;
$this->load->view('edit',$data);
}
function update($id)
{
$id=$this->input->post('id');
$data=array(
'studentname' => $this->input->post('studentname'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('phone')
);
$this->db->where('id',$id);
$this->db->update('tblstudent',$data);
redirect("Student/index");
}
function delete($id)
{
$id=$this->db->where('id',$id);
$this->db->delete('tblstudent');
redirect("Student/index");
}
}
My model
class StudentModel extends CI_Model{
function _construct()
{
parent::_construct();
}
function gettable()
{
$query=$this->db->get('tblstudent');
return $query->result();
}
function getonerow($id)
{
$this->db->where('id',$id);
$query = $this->db->get('tblstudent');
return $query->row();
}
}
For CodeIgniter 3.x: insert_batch
For CodeIgniter 2.x: insert_batch
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();