How to show data from (multidimensional?) arrays with Laravel 5.3 blade - arrays

Ok, so this is a question I hope can help other newbies as I'm running into errors pulling information from arrays in Blade and I'm unfamiliar with it's syntax to properly debug.
I understand how to send array data to the view normally, for instance:
public function index() {
$variable = DB::table('tablename')->where('ID', '535');
return view('viewname', compact('variable'));
}
This will send everything attached to the ID of 535 to the view. The title can then be printed out like so:
#foreach ($variable as $foo)
{{ $foo->title }}
#endforeach
Or if you want to print everything (I Think this is right?):
#foreach ($variable as $foo)
#foreach ($foo as $name)
{{ $name }}
#endforeach
#endforeach
That process I kind of understand.
But where I'm getting stuck is with models.
Let's say I set up some routes:
Route::get('User', 'UserEntryController#index');
route::get('User/{id}', 'UserEntryController#show');
And in the controller one that grabs the show route:
<?php
namespace App\Http\Controllers;
use App\UserEdit;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserEntryController extends Controller
{
public function show(UserEdit $id) {
return $id;
}
}
This will return everything attached to the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserEdit extends Model {
protected $table = 'users';
protected $fillable = ['ID', various', 'pieces', 'of', 'table', 'data'];
protected $hidden = [];
protected $casts = [];
protected $dates = [];
}
However if I change a line on the controller:
<?php
namespace App\Http\Controllers;
use App\UserEdit;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserEntryController extends Controller
{
public function show(UserEdit $id) {
return view('UserEdit', compact('id'));
//return $id;
}
}
The aforementioned Blade code will not run. In fact, I can't parse the array sent out to the the view at all. Of course a straight {{ id }} will give me the actual contents of the array.
{"ID":535,"various":"Del","pieces":"22","of":"32","table":"54","data":"John"}
So I guess my question is. If I'm getting data that's in the form of an array like this. How do iterate through it to apply formatting, put it in tables, or put it in a form, etc?

You're naming convention actually confuses you.
As long as you're returning and using a Object, rename that $id variable to something more obvious.
like:
class UserEntryController extends Controller
{
...
public function show(UserEdit $object) {
return view('UserEdit', compact('object'));
}
...
}
For the case when your framework is not set to bind directly to the object and your show method receives the $id, than you should return the object by querying the DB.
class UserEntryController extends Controller
{
...
public function show($id) {
$object = UserEdit::findOrFail($id);
return view('UserEdit', compact('object'));
}
...
}
... and nou in your view blade file you can use it like in your above examples.
#foreach ($object as $foo)
#foreach ($foo as $name)
{{ $name }}
#endforeach
#endforeach`

Related

Passing JSON from controller to view in codeigniter

I made an API call and received the response in JSON format.
JSON:
{
"Specialities": [
{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},
{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},
{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}
]
}
Controller File:
public function index(){
$data= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
Above code doesn't work because in view I can't access the nested object properties. However I am able to echo the JSON properties in controller file just like this:
Controller File:
public function index(){
$data=json_decode(file_get_contents('some_url'));
foreach ($data as $key=>$prop_name){
for($i=0;$i < count($prop_name);$i++){
echo $prop_name[$i]->SpecialityID;
echo $prop_name[$i]->SpecialityName;
}
}
}
My question is how do I pass this JSON to view and how can I access those properties in view file?
In controller changes like
public function index(){
$data['json_data']= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
and in the view
echo "<pre>";print_r($json_data);
As per Docs
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading method.
Here is an example using an array:
So you need to change your code in controller
Controller.php
$data = array();
$data['myJson'] = json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
my_view.php
<html>
....
<?php
//Access them like so
print_r($myJson);
// Rest of your code here to play with json
?>
....
</html>

Respond as XML not working since cakePHP 3.1

I need to render an XML+XSL template in my application, and it used to work with cakePHP 3.0. I have made the switch to 3.1 recently and it has stopped working. The problem is that I was having a formatted view of my XML, while now I just get a plain string.
The migration guide says something about some changes in the RequestHandlerComponent, but nothing helpful (or maybe it's just me and I don't get the point :)).
This is my controller (it is exactly as it was with Cake3.0):
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Utility\Xml;
use Cake\Event\Event;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Filesystem\Folder;
use Cake\Filesystem\File;
use Cake\Network\Email\Email;
use Cake\Core\Configure;
use Cake\I18n\Time;
/**
* Invoices Controller
*
* #property App\Model\Table\InvoicesTable $Invoices
*/
class InvoicesController extends AppController
{
public $components = [
'Browser',
'Reorder11'
];
public $helpers = [
'Multiple'
];
public $paginate = [];
public function initialize()
{
parent::initialize();
$this->loadComponent('Paginator');
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['demo']);
}
/*
* ... several other functions ...
*/
public function viewxml($id = null)
{
$this->viewBuilder()->layout('xml');
$invoice = $this->Invoices->myInvoice($id, $this->Auth->user('id'));
$this->RequestHandler->respondAs('xml');
$this->set('invoice', $invoice);
}
}
The xml.ctp layout, which is really simple
echo $this->fetch('content');
and the viewxml.ctp template just echoes the xml as a string.
How can I obtain the formatted XML+XSL again?
Try add: $this->response->header(['Content-type' => 'application/xml']);
I had the same error but my output was pdf
working 3.0.14 using this code:
$this->RequestHandler->respondAs("pdf");
$this->layout = 'pdf/default';
$this->view = 'pdf/report1_pdf';
for 3.1.x (this works if u save the file and open later, if you try to open it directly on browser its print the plain file content as a txt/html):
$this->viewBuilder()->layout('pdf/default');
$this->viewBuilder()->template('pdf/report1_pdf');
$this->RequestHandler->respondAs('pdf');
$this->response->header(['Content-type' => 'application/pdf']);

How to get variable from AppController beforeFilter in Other Controllers action in cakePHP 2.0

I have queried on the User table inside the AppController as below
<?php
class AppController extends Controller {
public function beforeFilter() {
function beforeFilter() {
parent::beforeFilter();
if ($this->Session->read('Auth.User.id')) {
$userLoginInfo = $this->User->findByUserId($this->Session->read('Auth.User.id'));
$this->set('userLoginInfo', !empty($userLoginInfo) ? $userLoginInfo : NULL);
}
}
}
}
?>
The $userLoginInfo is available in all ctp files, but I want to access it in all other controller actions as well.
now you put this code in AppController
function beforeFilter(){
$this->set(‘accesstest’ , ‘abc’);
}
And We have to use it in Other controller file say anotherController.php
then we will use $this->viewVars.
here we will be used
$test = $this->viewVars[‘accesstest’];
$this->set('test',$test);
Your own answer is applicable if wanting to set a variable for all Views, but this was not what you were asking in your question.
If you are extending AppController correctly then you can create a property of the AppController class that would then be accessible from any controller that extends it:-
class AppController extends Controller {
public $accesstest = 'abc';
}
Then in any controller that extends AppController you can use:-
$test = $this->accesstest;
echo $test; // 'abc'
However, if you want to share a variable that you want accessible from all controllers that can be changed and you want the change remembering then use the Session:-
$this->Session->write('accesstest', 'abc');
$test = $this->Session->read('accesstest');
$userLoginInfo = $this->viewVars['userLoginInfo'];

Cakephp elements and for each loops

I'm breaking my head some time now on the following cakePHP code:
This is my controller:
<?php
class HeaderController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
}
public function usp() {
return $this->set('usp', $this->Header->query('SELECT * FROM USP WHERE Actief = 1'));
}
}
And this is my element:
<?
$UNSP = $this->requestAction('header/usp');
print_r($UNSP);
foreach($UNSP['header'] as $USPs):
echo $USPs['USP']['Naam'];
endforeach;
The query works and is executed when the page loads. I get an errormessage saying Invalid argument supplied for foreach() [APP/View/Elements/header.ctp, line 9]
Can somebody please help me with this?
You are assuming, somehow, that $UNSP in the view will be populated with the view variable you set in the usp() action. This is not how requestAction() works. requestAction() can either echo out the view that you call, or return the value of the function you're calling.
Instead, since it seems that usp() doesn't have a view but instead is just used to get data, you should return it like so
public function usp() {
return $this->Header->query('SELECT * FROM USP WHERE Actief = 1');
}
Then, in your view, tell requestAction() that you want the results of the function call:
$UNSP = $this->requestAction('header/usp', array('return'));
Now $UNSP should contain the results of the query.

cakephp find 'first' not pulling data

I have a link that calls:
<span style="margin-left:24px;">Print</span>
It plugs in the correct id, and my route sends it to the correct view file. I have a debug command to show the entire array for the print page, but I'm getting an empty array. Here is my controller code:
<?php
class CouponsController extends AppController {
public $name='Coupons';
public $uses=array('User', 'Coupon', 'Restaurant');
public $layout='pagelayout';
public function print_coupon($name=null) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$this->params['id'])));
$this->set('name', $f);
}
}
?>
Here is my Coupon Model:
<?php
class Coupon extends AppModel {
public $name='Coupon';
var $belongsTo=array(
'Restaurant'=>array (
'className'=>'Restaurant',
'foreignKey'=>'restaurant_id'
)
);
}
?>
and here is my Restaurant Model:
<?php
class Restaurant extends AppModel {
public $name='Restaurant';
var $hasMany=array(
'Coupon'=>array(
'className'=>'Coupon',
'foreignKey'=>'restaurant_id'
)
);
var $belongsTo=array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user'
)
);
}
?>
I have tried variations using
<span style="margin-left:24px;">Print</span>
along with in my controller:
public function print_coupon($name=null) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$this->params['id'])));
$this->set('name', $f);
}
as well as a few others, and whenever I debug($name) I get an empty array. I have had no problems associating Coupon with my other models for other tasks yet, but i think something may be wrong with my Restaurant Model.
For reference, I have these are equal to each other:
Restaurants.coupon = Coupon.id
Coupon.restaurant_id=Restaurant.id
The first anchor code you posted has a curly brace that shouldn't be there. When you use this:
<span style="margin-left:24px;">Print</span>
It should yield some url that's like this:
/coupons/print_coupon/75
Then in your CouponsController that 75 turns into the $name in your print_coupon parameters (with default routing settings), I recommend changing that to $coupon_id, so your function should look like this:
public function print_coupon($coupon_id) {
$this->set('title', 'Print your coupon');
$f=$this->Coupon->find('first', array('conditions'=>array('Coupon.id'=>$coupon_id)));
$this->set('name', $f);
}
Now $name should be accessible in your view. With this code above, $name won't exist within the controller.
I don't think $this->params exists in Cake 2.*. debug($this->request->params); You can get the params from there in the controller, though.

Resources