I have the following JSON. I am a newbie to both JSON and Laravel. I want to save each of the array objects like LineNum, StationName and StopNum into the DB. Any help is greatly appreciated. I have been able to parse, but unable to save them to DB.
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n <br />" ;
$trainDetail->Route = "$key";
} else {
echo "$key => $val\n <br />";
$trainDetail->StopNumber = "$key";
$trainDetail->StationName = "$val";
}
}
The Route is not storing the LineNum, the StopNumb is not storing the correct value.
Here is the JSON I am working on.
{"LineNum1":[{"StopNumber":"MN218","StationName":"ABCD"}],"LineNum2":[{"StopNumber":"MN244","StationName":"XYZ"}],"LineNum3":[{"StopNumber":"MN220","StationName":"DEFCG"},{"StopNumber":"MN318","StationName":"QWERTY"}]}
Any help is greatly appreciated.
Regards,
A normal query will return something like this,
[{"ID":"1","Code":"ECX4236"},{"ID":"10","Code":"LWJ3154"},{"ID":"11","Code":"TTX4201"},{"ID":"12","Code":"TTY2545"},{"ID":"13","Code":"RRA2553"}]
If you use Laravel's query format.
$items = DB::table('Items')->where('isActive','=',1)->pluck('Code');
this returns an array.
["ECX4236","LWJ3154","TTX4201","TTY2545","RRA2553"]
You can easily enter this into a database using Laravel. This is what I do.
Related
I want return the json data from my controller.
I have written belo code.
$this->loadModel('Users');
$query = $this->Users->find();
$users = $query->select(['id', 'name']);
echo json_encode($users);
This return data in below format:
[{"id":1,"news_type":1,"name":"hoge"},{"id":2,"news_type":1,"name":"hoge1"}]
but I want it in below format:
{"categories":[{"id":1,"news_type":1,"name":"hoge"},{"id":2,"news_type":1,"name":"hoge1"}]}
Found solution.
I have used this:
echo json_encode(array("users" => $users));
I am very new to the laravel framework and i have what it seems to be a simple question. I have a query like so
$query['query2']= DB::connection('test')->select(
"select * from cities");
...
...
echo json_encode($q);
Sometimes this particular query returns an empty result set.
How do I handle this? Lets say I want to add my own json response when its empty.
Thanks
Try the following
$dataToSend = $q->get(); // $q being your query
if($dataToSend->isEmpty())
{
echo json_encode(['something'=>'else']);
}
else
{
echo json_encode($dataToSend);
}
Or in a shorter fashion
$dataToSend = $q->get(); // $q being your query
echo json_encode($dataToSend->isEmpty()? ['something'=>'else'] : $dataToSend);
I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.
I am using laravel4 query builder . I have following query which returns json data .
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
The above query returns json format data , I want to convert this to arrat format . I know Toarray() is used in eloquent to convert this but here it is in query builder , please help me on this .
Thanks.
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
$array = json_decode($query);
Though i'm fairly sure that the query builder is not returning JSON.
The query builder returns an array of objects. For example the query:
$users = DB::table('users')->select('name')->get();
will return an array which you can handle like this
foreach($users as $user) {
echo $user->name;
}
EDIT
If you want to convert it to array you have to do it on your own.
Here is a quick way
$users = json_decode(json_encode($users), true);
Now you can handle it like this
foreach($users as $user) {
echo $user['name'];
}
I have pulled values from an xml file which i need to store. I now need to get this data into my mysql database. I have done a complex for each loop with multiple levels so I am wondering how I would go about putting this in to a MYSQL insert statement. Any help would be gratefully appreciated.
Example
<?php
$source = file_get_contents("test.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//market");
foreach ($game as $event)
{
if (strpos($event['name'], 'Match Betting') !== false)
{
mysql_query("INSERT INTO feed (feedid, homeid, homeodd, drawid, drawodd, awayid, awayodd)
VALUES ("echo $event['id'] .", ";
{
foreach ($event->children() as $prices)
{
echo $prices['id'] . ", ";
echo $prices['odds'];
}
}
")");
}
}
?>
The above really doesnt work and is a little stupid but I really cant think how to do this.
Help please :D
dont use foreach loop inside the mysql statement. instead use the sql in the foreach loop. try it and inform if it doesn't work.