Iterating through result set in Laravel controller - laravel

I am trying to simply iterate though a result set in laravel on the controller side. This is what I tried but I get the following error:
Cannot use object of type stdClass as array
Controller snippet:
$result = DB::select($query);
foreach($result as $r){
echo $r['email'];
}
I appreciate any help with this,
Thanks in advance!

You need to use it as an object:
$result = DB::select($query);
foreach($result as $r){
echo $r->email;
}
Or if for some reason you want to use it as array, you need to convert it first:
$result = DB::select($query)->toArray();
foreach($result as $r){
echo $r['email'];
}

After pulling data from database you can convert it to array but it is optional, it's depends on your necessity then you can simply use the foreach to loop through to each distinct object and get access their property
$data = DB:: table('categories')
->where('parent_id', $request->value)
->get()->toArray();
$output = '<option value="">Select '.ucfirst($request->dependent).'</option>';
foreach($data as $row){
$output.= '<option value="'.$row->id.'">'.$row->title.'</option>';
}
return response($output, 200);

The Laravel Collection class supports the standard methods for iterables: map, sort, filter etc. see: vendor/laravel/framework/src/Illuminate/Collections/Collection.php
if you're querying on a model:
$results = MyAwesomeModel::where('something' '=' 'other')->get();
//this is valid
$results->map(function($result) {
echo $result->field;
});
//this is also valid
for($i = 0; $i < sizeof($results); $i++){
echo $results[$i]->field;
}
I would suggest avoiding ->toArray() on hydrated results (instances of models) because you loose all the model properties.

Related

Remove JSON object value Laravel from MySql database

I want to remove JSON object value from mysql database via eloquent. I have tried with this code it works but I have to pass array key "$.language[1]".
Here is JSON object {"name":"The Lord of the Rings:The Fellowship of the Ring","language":["Hindi","English","Spanish"]} stored in database.
Here I want to remove English language from all the records.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use DB;
class BookController extends Controller
{
public function store(){
$book = new Book;
$book->attributes = $jsonAttr;
$book->save();
echo "Book saved";
die;
}
public function updateLanguage()
{
$result = Book::where('attributes->language','LIKE','%English%')->update(['attributes' => DB::raw('JSON_REMOVE(attributes, "$.language[1]")')]);
//$result = Book::where('attributes->language','LIKE','%H%')->get();
echo "<pre>";
print_r($result);
die;
}
}
Any help would be appreciated.
Where condition fetch all the match record from Database. You need to loop this query to remove particular book language. Try this code...
public function updateLanguage()
{
//Get all matched records from database
$result = Book::where('attributes->language','LIKE','%')->get();
//Loop items to get unique id
foreach($result as $key => $val){
$id = $val['id'];
$attr = json_decode($val->attributes, true);
$data = $attr['language'];
foreach($data as $itemkey => $lang){
if($lang == "English"){
//Pass unique id to remove language from book record
$result = Book::where('id',$id)->update(['attributes' => DB::raw('JSON_REMOVE(attributes, "$.language['.$itemkey.']")')]);
}
}
}
$result = Book::where('attributes->language','LIKE','%')->get();
foreach ($result as $key => $value) {
print_r($value['attributes']);
echo "<br>";
}
die;
}
You need json_decode for transform json to array : link
You remove "English" in array with unset : link
After that you can json_encode for transform array to json.

How to concatenate variables comes from model in controller

I need to concatenate variables come from model.I send the role_id from controller to model and get the role name according to its id.
controller:
function get_role_name(){
$data['rec']=$this->amodel->get_section();
foreach($data['rec'] as $i)
{
$name['x']=$this->amodel->get_name($i->role_id);
}
$this->load->view('sections',array_merge($data,$name));
}
I write $name['x'].=$this->amodel->get_name($i->role_id); but it shows the error which undefined index:x.How can I concatenate the role name in cotroller to send it to view?
you probably didnt define $name
$name = array();
// your foreach
foreach ()
btw, the concatenating was ok
$var = "foo";
$var .= "foo"
// will result in "foofoo"
If you want to append something using the .= syntax you need to make sure the variable or array exists first.
Try this:
function get_role_name(){
$data['rec']=$this->amodel->get_section();
$name = array();
foreach($data['rec'] as $i) {
if (isset($name['x'])) {
$name['x'] .= $this->amodel->get_name($i->role_id);
} else {
$name['x'] = $this->amodel->get_name($i->role_id);
}
}
$this->load->view('sections',array_merge($data,$name));
}

Laravel 4: Better way to create an array from an object than this

So I've retrieved an object from angular and need to convert it to an array.
The below works but I'm wondering if there's a cleaner or more efficient way to do this with Laravel:
$array = array();
foreach($input as $i){
$array[] = $i['brand_name'];
}
Thanks!
You can do it in one line:
$array = array_only($input, array('brand_name'));
if you need more than one value:
$array = array_only($input, array('brand_name', 'address'));

ez components fetch data using persistent object

I'm new to the eZComponents framework and I 'm using the Mvc Tools and persistent object to manipulate data from mysql.
I can get a single product on a page but I cannot list my products! Can someone help me with this code:
controller.php
public function doListproducts()
{
$ret = new ezcMvcResult;
$session = ezcPersistentSessionInstance::get();
$q = $session->createFindQuery('Product');
$objects = $session->findIterator($q, 'Product');
//$objects = $session->find($q, 'Product');
foreach ( $objects as $object )
{
$ret->variables['products'] = $object;
//$ret->variables['products'] = $object->getState();
}
return $ret;
}
template:
{use $products}
{foreach $products as $product}
{$article['product']}<br>{$product['body']}<br><br>
{/foreach}
The comments are different solutions but don't work either. Thanks for your help
{foreach $productsas $product}
Should be:
{foreach $products as $product}
Also:
{$article['product']}<br>{$product['body']}<br><br>
What is $article ?
Finally, did you check that $ret has the expected value ?

Codeigniter num_row returns "array" instead of number

Alright, Im trying to count all the rows where "Membership_Status" = Active. The result I get right now is "Array" instead of a number.
Here is my model
class Report_model extends Model
{
function count_members()
{
$query = $this->db->get_where('Membership', array('Membership_Status' => 'Active'));
return $query->num_rows();
}
}
Here is my controller
class Report extends Controller {
function YTD_report()
{
$data['main_content'] = 'report_membership_view';
$this->load->view('includes/template', $data);
}
}
Here is my view
report_model->count_members();
echo $total;
?>
My result is Array, where according to the db info, it should be 4.
What can I do/change to get it to display the proper number?
thanks
the $data array your passing to the view will create one variable for each key to be used by view...
So your controler once the model is loaded, you should do:
$data['total'] = $this->Report_model->count_members();
Then in the view you can use the $total variable like this:
<?php echo $total; ?>

Resources