Using a custom function in a Laravel 5 Controller - function

I'm using a Laravel 5, I just want to know how to use or declare a custom function inside my controller. I have
class UploadController extends Controller
{
function on_request_done($content, $url, $ch, $search) {
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode !== 200) {
print "Fetch error $httpcode for '$url'\n";
return;
}
$responseobject = json_decode($content, true);
if (empty($responseobject['responseData']['results'])) {
print "No results found for '$search'\n";
return;
}
print "********\n";
print "$search:\n";
print "********\n";
$allresponseresults = $responseobject['responseData']['results'];
foreach ($allresponseresults as $responseresult) {
$title = $responseresult['title'];
print "$title\n";
}
}
}
And whenever I call on_request_done inside one of my functions let's say,
public function getParallelApi()
{
define ('SEARCH_URL_PREFIX', 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&filter=0');
$terms_list = array(
"John", "Mary",
"William", "Anna",
"James", "Emma",
"George", "Elizabeth",
"Charles", "Margaret",
"Frank", "Minnie",
"Joseph", "Ida",
"Henry", "Bertha",
"Robert", "Clara",
"Thomas", "Alice",
"Edward", "Annie",
"Harry", "Florence",
"Walter", "Bessie",
"Arthur", "Grace",
"Fred", "Ethel",
"Albert", "Sarah",
"Samuel", "Ella",
"Clarence", "Martha",
"Louis", "Nellie",
"David", "Mabel",
"Joe", "Laura",
"Charlie", "Carrie",
"Richard", "Cora",
"Ernest", "Helen",
"Roy", "Maude",
"Will", "Lillian",
"Andrew", "Gertrude",
"Jesse", "Rose",
"Oscar", "Edna",
"Willie", "Pearl",
"Daniel", "Edith",
"Benjamin", "Jennie",
"Carl", "Hattie",
"Sam", "Mattie",
"Alfred", "Eva",
"Earl", "Julia",
"Peter", "Myrtle",
"Elmer", "Louise",
"Frederick", "Lillie",
"Howard", "Jessie",
"Lewis", "Frances",
"Ralph", "Catherine",
"Herbert", "Lula",
"Paul", "Lena",
"Lee", "Marie",
"Tom", "Ada",
"Herman", "Josephine",
"Martin", "Fanny",
"Jacob", "Lucy",
"Michael", "Dora",
);
if (isset($argv[1])) {
$max_requests = $argv[1];
} else {
$max_requests = 10;
}
$curl_options = array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_USERAGENT, 'Parallel Curl test script',
);
$parallel_curl = new ParallelCurl($max_requests, $curl_options);
foreach ($terms_list as $terms) {
$search = '"'.$terms.' is a"';
$search_url = SEARCH_URL_PREFIX.'&q='.urlencode($terms);
$parallel_curl->startRequest($search_url, 'on_request_done', $search);
}
$parallel_curl->finishAllRequests();
//return "Helloo";
}
I get
call_user_func() expects parameter 1 to be a valid callback, function 'on_request_done' not found or invalid function name
My route
Route::get('/parallelapi', 'UploadController#getParallelApi');
PLEASE NOTE THAT getParallelApi() is under UploadController as well.

The problem is you are passing in the name of the function but it has no idea what class that function exists in. You should be able to do this by passing an array as your callback with the first item being an instance of your controller and the second item being the name of the function.
$parallel_curl->startRequest($search_url, [$this, 'on_request_done'], $search);

Related

How to pass an array into laravel json?

Here my simple code..
$country=['Bangladesh','Pakistan'];
$capital=['Dhaka','Islamabad'];
return response()->json([
'country'=>$country,
'roll'=>$roll,
]);
If i run the above code ,the output will be like below..
{
"country": [
"Bangladesh",
"Pakistan"
],
"roll": [
'Dhaka',
'Islamabad'
]
}
But I want that my expected output will be like ..
EDIT: Following JSON is invalid (2 same key country)
{
{
"country":"Bangladesh",
"capital":"Dhaka"
},
{
"country":"Pakistan",
"capital":"Islamabad"
},
}
try this
$countries = ['India', 'Bangladesh', 'Pakistan'];
$capital = ['Delhi', 'Dhaka', 'Islamabad'];
$response = [];
foreach ($countries as $key => $country) {
$response[$key] = [
'country' => $country,
'capital' => $capital[$key],
];
}
return response()->json($response);
it will return
[{
"country": "India",
"capital": "Delhi"
},
{
"country": "Bangladesh",
"capital": "Dhaka"
},
{
"country": "Pakistan",
"capital": "Islamabad"
}
]
Your expected output is wrong. You simply cant have 2 same keys (country) in output json. You should have country and capital encapsulated in separate {}.

Undefined index: docs (View: /Applications/MAMP/htdocs/sep-api/resources/views/home.blade.php)

Hello I want to return a json value in a view from an api,
I am using GuzzleHttp,
but I have the following error
Undefined index: docs (View: /Applications/MAMP/htdocs/sep-api/resources/views/home.blade.php)
THAT'S MY JSON
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "*,score",
"q": "8092316",
"wt": "json"
}
},
"response": {
"numFound": 1,
"start": 0,
"maxScore": 5.1922903,
"docs": [
{
"nombre": "GUADALUPE",
"id": "8092316|C1",
"numCedula": "8092316",
"titulo": "LICENCIATURA EN CONTADURÍA",
"genero": "2",
"institucion": "UNIVERSIDAD VERACRUZANA",
"materno": "LUIS",
"anioRegistro": 2013,
"tipo": "C1",
"paterno": "LUIS",
"timestamp": "2020-09-02T06:20:01.7Z",
"score": 5.1922903
}
]
}
}
THAT'S MY CONTROLLER
public function index($cedulas)
{
$client = new Client([
'base_uri' => 'http://search.sep.gob.mx',
'timeout' => 300,
'Content-Type: application/vnd.api+json',
'Accept: application/vnd.api+json',
]);
$response = $client->request('GET', "http://search.sep.gob.mx/solr/cedulasCore/select?fl=%2A%2Cscore&q={$cedulas}&wt=json");
$posts = json_decode($response->getBody()->getContents(),true);
return view('home', compact('posts'));
THAT'S MY VIEW
#foreach($posts['docs'] as $post)
<h1>name: {{$post['nombre']}}</h1>
#endforeach
as doc is inside response key in json (as u mentioned)
#foreach($posts['response']['docs'] as $post)
<h1>name: {{$post['nombre']}}</h1>
#endforeach
or
$response = $client->request('GET', "http://search.sep.gob.mx/solr/cedulasCore/select?fl=%2A%2Cscore&q={$cedulas}&wt=json");
$responseData = json_decode($response->getBody()->getContents(),true);
$posts = $responseData['response'];

Why does this Laravel eloquent query give back more objects?

I am trying to get back a model that has relationships with other models in Laravel with eloquent but my query does not work. What i am trying to do is only
show the dataLog with the related groups, units and the related component and give that back as a object. The parameter $componentId is the only component that should be given back but it gives back other
component ids, groups and units aswell. Is there a way to only show the component with the given parameter componentId and skip the rest that is not relevant?
<?
public function getLogData( $componentId, $limit ) {
$dataLogs = Log::whereHas( 'groups', function( $group ) use (&$componentId) {
$group->whereHas( "units", function( $unit ) use (&$componentId) {
$unit->whereHas( "components", function( $component ) use (&$componentId) {
$component->where( "Component", $componentId );
} );
} );
} )->take( $limit )->get();
return response( )->json( $dataLogs );
}
?>
The response is
[
{
"Oid": 10409376,
"Active": false,
"Speed": "0",
"Weight": "0",
"Amount": "0",
"Code": "",
"Control": false,
"Type": 1,
"Event": 1,
"Name": "TestName",
"Number": "",
"Mode": 0,
"Recipe": "",
"DateTime": "2020-03-02 11:09:37.177",
"Check": 288,
"groups": [
{
"Oid": 11162074,
"Amount": "3.387",
"Cap": "0",
"Speed": "0",
"ActTachoVoltage": "0",
"Act": "0",
"Weight": "497717",
"Codes": "",
"Type": 1,
"Name": "Group1",
"units": [
{
"Oid": 15934577,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1102,
"Entry": 15934577
}
]
},
{
"Oid": 15934578,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1101,
"Entry": 15934577
}
]
},
}
]
The response that is needed with the given query
[
{
"Oid": 10409376,
"Active": false,
"Speed": "0",
"Weight": "0",
"Amount": "0",
"Code": "",
"Control": false,
"Type": 1,
"Event": 1,
"Name": "TestName",
"Number": "",
"Mode": 0,
"Recipe": "",
"DateTime": "2020-03-02 11:09:37.177",
"Check": 288,
"groups": [
{
"Oid": 11162074,
"Amount": "3.387",
"Cap": "0",
"Speed": "0",
"ActTachoVoltage": "0",
"Act": "0",
"Weight": "497717",
"Codes": "",
"Type": 1,
"Name": "Group1",
"units": [
{
"Oid": 15934577,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"Oid": 15934578,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1101,
"Entry": 15934577
}
]
},
}
]
If the parameter id given is 1101. Does any one know what i am doing wrong?
The models and the relation ships
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class log extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'log';
protected $connection = 'testdb';
protected $appends = [ 'groups' ];
// Functions
public function getGroupsAttribute( )
{
if( $this->groups() )
return $this->groups()->get();
return [];
}
// Define model relationship logEntry = FK from log to group model
public function groups(){
return $this->hasMany(groupLog::class, 'logEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class groupLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'groupLog';
protected $connection = 'testdb';
// Functions
public function getUnitsAttribute( )
{
if( $this->units() )
return $this->units()->get();
return [];
}
// Define database relationships
public function log(){
return $this->belongsTo(log::class);
}
// Define model relationship groupEntry = FK from log to group model
public function units(){
return $this->hasMany(unitLog::class, 'groupEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class unitLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'unitLog';
protected $connection = 'testdb';
protected $appends = [ 'components' ];
// Functions
public function getComponentsAttribute( )
{
if( $this->components() )
return $this->components()->get();
return [];
}
// Database relationships with models
public function group(){
return $this->belongsTo(groupLog::class);
}
public function components(){
return $this->hasMany(componentLog::class, 'unitEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class componentLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'componentLog';
protected $connection = 'testdb';
// Define model database relationships
public function units(){
return $this->belongsTo(unitLog::class);
}
}
?>
Tried the solution with the answer like so
$machineLogs = MachineLog::whereHas( 'groups', function($group) use ($componentId) {
$group->whereHas( "units", function( $unit ) use ($componentId) {
$unit->whereHas( "components", function( $component ) use ($componentId) {
$component->where("component", $componentId);
} );
} );
} );
$filterComponents = $machineLogs->with(['groups.units.components' => function ($query) use ($componentId) {
$query->where('component', $componentId);
}])->take($limit)->get();
return response( )->json( $filterComponents );
You are querying Log that has the given units and it will always return all the units, no matter what ids they have. What you are looking for is to filter the relationship using with(). I would still use your full query, for getting the correct logs out.
Log::yourQueries() // insert your existing queries here.
->with('groups.units.components' => function ($query) use ($componentId) {
$query->where('component', $componentId);
});
This will preload components and filter them by the giving query, this should return your expected result.

Json response in Codeigniter

Below is the code for user list webservice's json response.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Webservice extends CI_Controller
{
function list_user()
{
$result_login = $this->db->get('user_registration')->result();
$response = array();
$response ["success"] = 1;
$response ["message"] = "User List.";
foreach($result_login as $row)
{
$data = array();
$data['User Id'] = $row->user_id;
$data['Name'] = $row->name;
$data['Email'] = $row->email;
$data['mobile_number'] = $row->mobile_number;
$data['Password'] = $row->password;
$output2 = json_encode(array('responsedata' => $data));
echo $output2;
}
}
}
?>
In my code if i replace $data with $response in json_encode then i can't get $data's value.
I got json response in this format. JSON Response.
{
"responsedata": {
"User Id": "7",
"Name": "bhavin",
"Email": "bhavin123#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
}
But i want json response in this format.
{
"responsedata":
{
"success": 1,
"data": [
{
"User Id": "7",
"Name": "test",
"Email": "test1#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
},
{
"User Id": "8",
"Name": "test2",
"Email": "test2#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
]
}
}
You need to arrange Your array like this
I update below code
$array_of_event = array()
foreach($result_login->result_array() as $row)
{
$array_of_event[] = $row;
}
$data['success'] = "1";
$data['data'] = $array_of_event; //need to assign event here
$response['responsedata'] = $data;
echo json_encode($response);

symfony json_respone withprefix

i create a route with json_respone function.
the code:
/**
* #Route("/app/homec")
*/
public function HomeCatsAction(Request $request) {
$list = $this->getDoctrine()
->getRepository('AppBen2Bundle:HomeCategories')
->createQueryBuilder('e')
->getQuery()->getArrayResult();
$response = new JsonResponse($list);
$response->headers->set('Content-Type', 'application/json; charset=UTF-8');
$response->setStatusCode(200);
return $response;
}
the json show it's fine, but no prefix.
exp:
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
i want that the response will be:
home_categories": [
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
]
my current symfony 2 version is 2.6
i try many solutions but the same result
This should work:
$response = new JsonResponse(array('home_categories' => $list));