Make request (pass data) from Command File to Controller in Lumen/Laravel - laravel

i get data (query) in command file and want to pass to controller via API (route)
here my request code in command file :
$request = Request::create('/create_data_account', 'post', ['data'=>$data]);
$create = $app->dispatch($request);
this is the route :
$router->post('/create_data_account', 'APIController#create_account_data_api');
and my controller :
public function create_account_data_api(Request $request)
{
$count = 0;
foreach ($data as $key => $value) {
$insert = Account::create([
'account_name' => $value->account_name,
'type' => $value->type,
'role_id' => $value->role_id
]);
if($insert){
$count++;
}else{
return $response = ['result'=>false, 'count'=>$count, 'message'=>'Internal error. Failed to save data.'];
}
}
return $response = ['result'=>true, 'count'=>$count, 'message'=>'Account data saved Successfully'];
}
i'm confused why passing data to controller not working with that code. anyone can give me solution ? Thanks

As you are making the request with ['data'=>$data]. That means all the data is contained on the key data of your array. So before the foreach loop, you need to add a declaration statement $data = $request->input('data'); to get data in $data variable.

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Data stored in cache is null (Cache driver: array)

I tried to store data in cached but when I retrieved the cached it returns null.
My cache driver is CACHE_DRIVER=array
and here is my controller...
public function index(Request $request){
view()->share('page_sub', 'Webhhook');
$data = Cache::get('repo');
dd($data);
return view('webhook.index', compact('data'));
}
public function handle(Request $request){
// $data = $request;
$admins = User::whereHas('roles', function($q){$q->whereIn('roles.name', ['superadmin']);})->get();
$data = [
'id' => $request['repository']['id'],
'name' => $request['repository']['name'],
'tags_url' => $request['repository']['tags_url'],
'archive_url' => $request['repository']['archive_url'],
'updated_at' => $request['repository']['updated_at'],
];
$now = \Carbon\Carbon::now();
$repo_data = cache('repo');
\Log::info($repo_data);
if ($data['updated_at'] != $repo_data['updated_at']) {
Cache::put('repo', $data, $now->addMonth(1));
}
foreach($admins as $user){
$user->notify(new WebhookNotification($repo_data));
}
}
when I dd($data) from this $data = Cache::get('repo'); the result is null
Any ideas?
Thank you.
CACHE_DRIVER=array only stores data in cache for functions used in same request and expires as soon as response is sent to browser.
If you want to access cache data in multiple request you can use CACHE_DRIVER=file this will save your data in files which can be accessed later.

how to inject a file into http request

i have a test case:
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>Storage::get('file/file.xlsx')]);
$response->assertJsonFragment(['a'=>'b']);
my controller:
public function import(Request $request, Unit $unit)
{
$this->validate($request, [
'file' => 'file|required_without:rows',
'rows' => 'array|required_without:file',
'dry_run' => 'boolean',
]);
if ($request->has('rows')) {
//
} else {
$results = $request->file('file');
}
return "ok";
}
but i think my test case is wrong,because when i dd($reuqest->file('file')) in my controller, it return null.
So, how can i request file into my controller.
please help
You can use UploadFile like this:
$fileName= 'file.png';
$filePath=sys_get_temp_dir().'/'.$fileName;
$mimeTypeFile=mime_content_type($filePath);
$file=new UploadedFile($filePath, $fileName, $mimeTypeFile, filesize('$filePath'), null, true)
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>$file]);
$response->assertJsonFragment(['a'=>'b']);
with null is The error constant of the upload, true is test mode
more detail for Symfony UploadedFile, read this
As mentioned in this https://laravel.com/docs/5.4/http-tests#testing-file-uploads.
Try something like this. Import use Illuminate\Http\UploadedFile;
UploadedFile::fake()->create('file.xlsx', $size);
Storage::disk('file')->assertExists('file.xlsx');

Can't read $this->post('username'); in rest server from input form rest client

Why $this->post('username') can not read input from rest client ?
In my controller for server :
function login_post(){
$data['username']=$this->post('username');
$data['password']=$this->post('password');
if ($this->get('cobak')==1) {
$cek = $this->model_user->ambilPengguna($data);
}
if ($cek) {
$this->response($cek, 200); // 200 being the HTTP response code}
else {
$this->response(array('error' => 'User could not be found'), 404);
}
}
My models :
public function ambilPengguna($data) {
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->where($data);
$query = $this->db->get();
return $query->num_rows();
}
And this is my client controller :
public function proses_login(){
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$cek = $this->rest->post('login/cobak/1/format/php/');
echo $cek;
}
The result from query is 5. It means read all record in database table
You send data by URL method you can send data instead as the following
for more information about URL method you can read this
$cek = $this->rest->post('login', $data, 'php');
you can recieve data in server by two ways
$this->post('username') or $this->input->post('username')
I think it may work
you can get more details from : Here

Problems using batch_update in codeigniter

I read similar batch_update Qs but I still have issues. Thanks in advance for help! I receive error message ("One or more rows submitted for batch updating is missing the specified index.") for the following code:
Controller:
public function do_edit_page(){
$id = $this->input->post('page_id', TRUE);
$link_title = $this->input->post('page_link_title', TRUE);
$link = $this->input->post('page_link_sub_title', TRUE);
$this->content_model->update_links($id, $link_title, $link);
$this->index();
}
Model:
public function update_links($id, $link_title, $link){
$data = array(
array(
'page_id' => $id,
'link_title' => $link_title,
'link' => $link
)
);
$this->db->update_batch('content_links', $data, $id);
}
Check the CI documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
so the third parameter should be a column not data.

Resources