I want to populate an array with ids that are fetched from db table. Later I want to fetch those ids from the array to insert into another db table. Below is the code:
public function storeBaritems()
{
$id = Auth::user()->id;
$bartypearray = array();
$bartypes = request('select1'); // <select id="select1" name="select1[]"
foreach ($bartypes as $type) {
$bartypearray[] = Bartype::select('bartype_id')
->where('bar_type_name','like',$type)
->where('restaurant_id', $id)
->get();
}
$baritems = request('itemname'); //<input type="text" class="hookah-field" name="itemname[]">
$descriptions = request('description'); //<input type="text" class="hookah-field" name="description[]">
$quantity = request('quantity'); //<input type="text" class="hookah-field" name="quantity[]">
$prices = request('price'); //<input type="text" class="hookah-field" name="price[]">
$i = 0;
foreach ($bartypearray as $item) {
Bar_menu::create([
'item_name'=>$baritems[$i],
'description'=>$descriptions[$i],
'quantity'=>$quantity[$i],
'price'=>$prices[$i],
'res_id'=>$id,
'type_id'=>$item->bartype_id
]);
$i += 1;
}
}
The HTML form dynamically creates new fields with same "name" attribute. Right now, I am getting the error - "Exception in Collection.php line 1527:
Property [bartype_id] does not exist on this collection instance." Any solution would help. Thanks
You could use the pluck method.
$bartypearray = Bartype::where('bar_type_name','like',$type)
->where('restaurant_id', $id)
->pluck('bartype_id');
With this method there is no need for the first foreach.
BTW. I would highly recommend to loo into all collection methods
Related
I need to add a drop-down menu that filtrates with enum values from the table. Instead of that it gets the values from the rows. Any and all help gratefully received.
This is what I have managed to get so far.
View:
<div>
<span>
<select class="mb-2">
<option value="Status" disabled selected>Status</option>
#foreach ($status_filter as $key => $status)
<option value="{{ $key }}">
{{$status}}
</option>
#endforeach
</select>
</span>
</div>
Controller:
$status_filter = Competition::pluck('status');
$request->flash();
return view('competition.index', compact('competitions', 'status_filter'));
This is what I need to get from the migration:
$table->enum('status',['inactive','to_push','active'])->default('inactive');
You can grab those enum values from the table. But there is no direct way. You have to use laravel query builder using raw.
$statusValues = DB::select(DB::raw("SHOW COLUMNS FROM competitions WHERE Field = 'status' "))[0]->Type;
$matches = array();
preg_match('/^enum\((.*)\)$/', $statusValues, $matches);
$enumValues = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enumValues = $v;
}
print_r($enumValues)
If i got it right you want to make a filter for status like listing all active ou inactive. I think the easiest way to do this is add a query on your variable $status_filter on the controller. Something like: $status_filter = Competition::where('status', 'active')->pluck('status');
As #SazzadHussain suggested adding this block of code inside my model class solved the issue.
public static function getPossibleEnumValues($table, $column) {
$type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enum = Arr::add($enum, $v, $v);
}
return $enum;
}
After that getting it from my Controller like that:
$enumoption = Competition::getPossibleEnumValues('competitions','status');
I'm new to Lumen and trying to make a simple REST API app. I want one of the endpoints to be able to display all records from a "storeItems" table but add a field to each record with its' categories and paginate them.
So at the moment I have the usual
$products = DB::table('storeItems as i')
->where('i.B2BAvailable', '=', '1')
->select('i.title','i.EAN','i.vendor','i.productType','i.ID as productID','i.releaseDate',DB::raw('(CASE WHEN (i.releaseDate > NOW()) THEN 1 ELSE 0 END) AS announced'))
->orderBy('i.releaseDate', 'desc')
->paginate(100);
return response()->json($products);
This gives out the expected result, but if I want to iterate over the results and add a field from a different table...like this:
foreach($products as $product) {
$genres = DB::table('sCategoryConnector as ggc')
->join('sCatGenre as gg','gg.ID','=','ggc.ID_sCatGenre')
->where('ggc.EAN', '=', DB::raw("'".$product->EAN."'"))
->select('gg.tag')
->orderBy('gg.ID', 'asc')
->get();
if (count($genres) > 0) {
$i=0;
foreach($genres as $genre) {
//$product['genres'][$i] = $genre['tag'];
$propName = 'genre'.$i;
$product->genres->$propName = $genre->tag;
$i++;
}
}
}
But Lumen is outputting: Creating default object from empty value error and marking this line:
$product->genres->$propName = $genre->tag;
What am I doing wrong? Thanks up front.
So I was rushing a bit...should have replaced assigning genres like this:
if (count($genres) > 0) {
$i=0;
$product->genres = $genres;
/*
foreach($genres as $genre) {
//$product['genres'][$i] = $genre['tag'];
$propName = 'genre'.$i;
$product->genres->$propName = $genre->tag;
$i++;
}
*/
}
So the correct way to assign a new property to a StdClass object....
$product->genres = $genres;
I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!
I want to create a form using a table where a column generates the questions( nom ) and another one generates the type of the response(type ) that can be (text, date, checkbox, radio etc ...), I was able to generate the questions however I wasn't able to determinate the type.
I am really struggling to use the type column in my champs table as a variable of input types in a form.
Any help would be extremely appreciated
to clarify more here are my codes:
ChampsModel.php
<?php
require_once("../config/database.php");
function Champsbyqid($qid){
$c = Database :: connect();
$results = array();
$q = $c -> prepare ("SELECT nom FROM champs WHERE qid=?") ;
$q -> execute (array($qid));
while ($data = $q -> fetch()) {
$results[] = $data;
}
Database :: disconnect();
return $results;
}
function getType($qid){
$c = Database :: connect();
$results = array();
$q = $c -> prepare ("SELECT type FROM champs WHERE qid=?") ;
$q -> execute (array($qid));
while ($data = $q -> fetch()) {
$results[] = $data;
}
Database :: disconnect();
return $results;
}
?>
ChampsController.php
<?php
require_once("../model/champsModel.php");
$champs = Champsbyqid(1);
$type = getType(1);
?>
Champs.php
<?php
require_once("../controller/champsController.php");
foreach ($champs as $value) {
foreach ($types as $val) {
echo $value['nom'].'<form method="POST"><input type='$val['type']'></form>';
}
}
?>
?>
You are generating each question repeatedly for every type retrieved, you don't need the second foreach loop. I would also suggest using a single query to fetch both values, then you can simple use $value['nom'] and $value['type']. But if you need to keep them separate, just use
for ($i = 0; $i < count($champs); $i++) {
echo $champs[$i]['nom'].'<form method="POST"><input type='$type[$i]['type']'></form>';
}
you're going to want to SELECT * FROM WHERE qid = ORDER BY ordre; <-- is this a type that is suppose to be order?. Get the rows as an associative array, in a variable, lets say $value. Then,
<form method="" action="">
while (there are rows) {
echo $value["nom"].'<input type="'.$value["type"].'"
name="whatever"><br />';
}
</form>
Be weary of reserved words in your programming languages. Some words you can't use as variables.
I'm trying to get my head around grabbing all variable I need in Codeigniter and then passing those values to the view.
I understand the concept, but am getting stuck on iterating through an array and adding on another array to each of its keys.
The $data['items'] array contains data passed from a model via the get_all() function. The query is basically "Select * from items".
Each item has multiple features and pictures. In order to get the appropriate values I need the id of an item. I can grab this from the first array ($data['items']) which I can then pass to a model function.
I keep getting various errors when trying to do this via the code below. I've tried defining the features and pictures arrays before the foreach loop - still get errors.
I'm sure my syntax is just wrong. Any help is welcome.
$data['items'] = $this->amazon->get_all();
foreach ($data['items'] as $data )
$id = $data->id;
$data['features'] = $this->amazon->get_features($id);
$data['pictures'] = $this->amazon->get_pictures($id);
}
Edit
Based on feedback I've updated the code to this (lines 24 - 30 of the code):
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++) {
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}
PHP is complaining with this:
PHP Fatal error: Cannot use object of type stdClass as array in /var/www/ci/application/controllers/main.php on line 28
Here are the functions from the amazon model:
function get_all()
{
$query = $this->db->get('items');
return $query->result();
}
function get_pictures($id) {
$query = $this->db->query("SELECT link FROM pictures WHERE item_id='$id' AND type IN('thumb_set')");
$style = "border-style:solid; border-width:1px";
$class = "modal-thumb";
$results = '';
foreach ($query->result() as $row) {
$results .= "<li style='$style' class='$class'><img src='$row->link' alt=''/></li>";
}
return $results;
}
function get_features($id) {
$query = $this->db->query("SELECT content FROM features WHERE item_id='$id' ORDER BY feature_num DESC");
$results = '';
foreach ($query->result() as $row) {
$results .= "<li>";
$results .= $row->content;
$results .= "</li>";
}
return $results;
}
I'm thinking i need to use 'results_array()' instead of 'results()'? Are my results returned as an object instead of an array the way things are now?
As you said, you have syntax error in the foreach statement, you are redefining the $data array.
foreach ($data['items'] as $data )
Try this:
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++){
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}