I am simply (for my own testing purposes) trying to take data from a collection and pass it to a view. I am using Laravel.
I am getting my data from the GitHub API, converting it and putting it in a collection. From here it's passed to a view, but I can't output each individual field.
Here's some code:
$httpClient = new Client();
$response = $httpClient->get('https://api.github.com/users/<randomuser>');
$json = json_decode($response->getBody(), true);
$collection = collect($json);
return view('github')->with('github', $collection);
and my Blade file is
#foreach ($github as $git)
{{ $git }}
#endforeach
Now I thought it would be something as simple as {{ $git->email }} to output it, but I don't think the array keys are been sent (?)
Can anybody point me in the right direction of where I am going wrong?
Thanks in advance.
-Chris
Because it's a key => val array, you should loop it as such...
#foreach ($github as $key => $val)
Key: {{ $key }} ~~ Value: {{ $val}} <br />
#endforeach
However if you are looking to just grab the email, use the Collection's get method.
$email = $github->get('email')
Simple use get() method in your blade
$github->get('login')
Try this,
in your controller use View and in function
$data['github_data'] = $collection;
return view('github', $data);
and in blade
{{ dd($github_data) }}
When you are working with Laravel try to check if you have the correct structure before trying to manipulate it.
In this case, check that:
You are getting what you expect in $response after call $httpClient->get (if you are using Guzzle).
You have a $json with the structure that you expect to receive.
You have a Collection instance after calling collect().
You can use dd() or var_dump() to see what data structure you have. What´s probably happening is that you don´t have the structure that you think.
Related
I go this error:
htmlspecialchars() expects parameter 1 to be string, object given
I'm using in controller:
$data = '{"pr":{"code":"1"},"ac":[[{"icon":"web","action":"link","url":"asd"}]]}'
$newData = json_decode($data);
And i send it to the view as array: 'data' => $newData
And when i try to use $data into the view, it give me that error
Tried already to use $data->ac OR $data['ac'] but still the same...
Some help, please?
When you use a blade echo {{ $data }} it will automatically escape the output. It can only escape strings. In your data $data->ac is an array and $data is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }} (not sure why you have two nested arrays but I'm just following your data structure).
#foreach($data->ac['0'] as $link)
This is a link
#endforeach
if you real intention is to send the full array from the html to the controller, you can use the following code:
from the blade.php:
<input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}">
in controller
public function Get(Request $req) {
$quotation = array('quotation' => json_decode($req->quotation));
//or
return view('quotation')->with('quotation',json_decode($req->quotation))
}
You could use serialize
<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">
But best way in this case use the json_encode method in your blade and json_decode in controller.
This is the proper way to access data in laravel :
#foreach($data-> ac as $link)
{{$link->url}}
#endforeach
Try use in your collection the json_encode().
https://www.php.net/manual/pt_BR/function.json-encode.php
public static function getTeamMemberInto($user_id){
$team = DB::table('members_team')
->join('teams', 'teams.id', '=', 'members_team.teams_id')
->join('employees', 'employees.id', '=', 'teams.leader_employees_id')
->where('members_team.employees_id', '=', $user_id)
->select('*')->first();
// dd($team);
if($team){
return json_encode($team, true);
}else{
return false;
}
}
I've an error like Trying to get property of non-object, I use var_dump and realize that I've array not object but idk how to access
public function ptkp($id){
$halaman="tindaklayanan";
$keluhan = keluhan::findOrFail($id);
$tindak = DB::table('tindakans')
->join('keluhans','keluhans.id','=','tindakans.id_keluhan')
->select(DB::raw('tindakans.id, id_keluhan, perbaikan_sementara, revisi_dokumen, target_verifikasi, ttd_tanggung1,
ttd_tanggung2'))->get();
$analisa = DB::table('analisas')
->join('tindakans','tindakans.id','=','analisas.id_tindakan')
->join('keluhans','keluhans.id','=','tindakans.id_keluhan')
->select(DB::raw('id_tindakan, analisa, tindakan, pic, tanggal_pelaksanaan'))->get();
return view('Laporan.ptkp',compact('keluhan','tindak','analisa','halaman'));
//$pdf = \PDF::loadView('laporan.ptkp', compact('keluhan','tindak','analisa','halaman'));
//return $pdf->stream();
}
Look at $tindak when I use var_dump the result is array, in View I try to access using <?php echo $tindak->perbaikan_sementara ?> but error.
Since you are in Laravel, I assume you use a blade templating engine, so you can try this in the view to access property of object :
{{ $tindak->perbaikan_sementara }}
Or if it's an array of objects :
#foreach ($tindak as $example)
{{ $example->perbaikan_sementara }}
#endforeach
if you really have an array it's in your Laporan.ptkp (better use laporan.blade.php instead)
#foreach ($tindak as $item)
{{ $item['perbaikan_sementara'] }}
#endforeach
I need to check for a name in an array of names but I having trouble passing an array instead of a collection to the in_array() method.
My blade code looks something like this
#foreach($ecn->areas as $area)
{{ $area->area }}:<br>
<ul>
#foreach($area->people as $person)
#if(in_array($person, $ecn->signatures->name ))
<li><del>{{ $person }}</del></li>
#else
<li>{{ $person }}</li>
#endif
#endforeach
</ul>
#endforeach
I know my problem is in the way im trying to access the list of signatures.
#if(in_array($person, $ecn->signatures->name ))
I can access them in another part of the page doing this
#foreach($ecn->signatures as $signature)
{{ $signature->name }}<br>
#endforeach
and everything is fine.
How can I access and pass the list of signatures as an array in this scenario?
If you want to use in_array() version for Laravel Collections then you can use:
$collection->contains($needle)
It woks just like in_array.
If $needle is an integer, an id for example, don't forget to pluck first, like so:
$collection->pluck('id')->contains($needle)
You can use the lists or pluck method on the signatures collection to get a new collection of all the names. From there, you can either use the contains() method on the collection, or you can use the all() method to turn the collection into an array and use in_array directly.
I would suggest doing this outside of the foreach loop, so you're not generating this new collection and array every iteration.
Array:
// controller
$names = $ecn->signatures->lists('name')->all();
// blade
#if(in_array($person, $names))
Collection:
// controller
$names = $ecn->signatures->lists('name');
// blade
#if($names->contains($person))
You can also use contains() with a closure, which would let you get away with not creating an intermediate collection, but it's a little harder to read:
Contains with closure:
// blade
#if($ecn->signatures->contains(function ($key, $value) use ($person) {
return $value->name == $person;
}))
As per Laravel Docs
The get method returns an array of results where each result is an instance of the PHP StdClass object.
So you must convert your stdClass object to a array in your controller itself.
foreach ($ecn->signatures as $signature)
$nameArray[] = $signature->name;
and then you can use in_array in the blade template
#if(in_array($person, $nameArray))
I use ::find to find the business but business_position I need to use WHERE business_id = and WHERE id to find the correct position, and example is avalible below...
<?php
$s = Stats::find(Auth::user()->id);
$myJob = \App\Businesses::find($s->business_id);
$matchedValues = ['business_id' => $s->business_id, 'id' => $s->business_position];
$myPosition = \App\BusinessPositions::where($matchedValues)->get();
?>
And using $myPosition I use
{{ $myPosition->pay_amount }}
And on that line it throws and error...
Undefined property:
Illuminate\Database\Eloquent\Collection::$pay_amount (View:
C:\Users\Darren\MyLavProject\resources\views\pages\business\business.blade.php)
Laravel's get() returns a collection of results that match your query (even if there are none or just one, it'll be an array of Laravel model instances).
You can use first() instead of get() to grab the first result, or you can foreach through each of the results get() provides. It depends if your application permits more than one permission per business_id/id combination.
$myPosition This is an array of objects.
So if you need the result:
{{ $myPosition[0]->pay_amount }}
Or
#foreach($myPosition as $position)
{{ $position->pay_amout }}
#endforeach
Of if you don't want to use any of these:
Change your query to :
$myPosition = \App\BusinessPositions::where($matchedValues)->first();
Now you can use: {{ $myPosition->pay_amount }}
Good afternoon
I recieve this JSON
{"id":130,"nif":"47812480B","name":"Bernat","cognoms":"Fernandez","file":"uploads\/fondo.jpg","birthday":"0000-00-00","presentacion":"presentacion","email":"bernat#gmail.com","password":"$2y$10$GfP1DYkTqyohjVzRcuuxaeKBSu7iJUBWJK6UDj7p681307uI6Ersq","idempresa":1,"id_poblacion":889,"id_online":0,"remember_token":null,"created_at":"2015-05-28 15:25:04","updated_at":"2015-05-27 15:25:04","municipio":{"id":889,"idprovincia":33,"poblacion":"Art\u00e9s","poblacionseo":"artes","postal":8271,"latitud":"41.798479","longitud":"1.954828"},"subastas":[{"id":16,"nombre":"HTC Wildfire","descripcion":"Descripcion","precio_salida":125,"cant_actual":125,"id_estado":0,"id_metode_envio":1,"id_metodo_pago":1,"id_creador":130,"id_ganador":125,"id_categoria":33,"id_adquirido":1,"data_inici":"2015-06-13","data_final":"2015-06-13","durada":1,"created_at":"2015-06-06 09:09:54","updated_at":"2015-06-06 09:55:49"}]}<p>34.884533408812</p> {"id":131,"nif":"263","name":"Lalo","cognoms":"Lelo","file":"uploads\/count.png","birthday":"0000-00-00","presentacion":"jejjsjsj","email":"vsdfsfaf#aasa.com","password":"$2y$10$QtrolUS9emCS7bfirsly9.JXt9AsYfAc.\/vA0iJCs47\/3g\/ypc8d6","idempresa":1,"id_poblacion":175,"id_online":0,"remember_token":"B1vEqdX8w42i7sLNvG201EArwSTrODe0DDzkVmjzj48ahMMV8oOLmzYRM5Mp","created_at":"2015-05-20 06:52:59","updated_at":"2015-06-06 08:35:13","municipio":{"id":175,"idprovincia":9,"poblacion":"Benej\u00fazar","poblacionseo":"benejuzar","postal":3390,"latitud":"38.083525","longitud":"-0.836494"},"subastas":[{"id":15,"nombre":"Nombre","descripcion":"Descripcion","precio_salida":142,"cant_actual":142,"id_estado":1,"id_metode_envio":1,"id_metodo_pago":1,"id_creador":131,"id_ganador":131,"id_categoria":33,"id_adquirido":1,"data_inici":"2015-06-18","data_final":"2015-06-17","durada":1,"created_at":"2015-06-06 00:00:00","updated_at":"2015-06-06 10:00:57"}]}<p>475.51158492016</p>
When I use the following foreach I show the information
#foreach ($subastas as $subasta)
{{$subasta}}
#endforeach
Now I try to use the following code
#foreach ($subastas as $subasta)
#foreach ($subasta->subastas as $sub)
{{$sub}}
#endforeach
#endforeach
And I recieve this error
Trying to get property of non-object (View: C:\xampp3\htdocs\laravel\resources\views\prodcercanos.blade.php)
Any solution for this problem ?
The question is , how I can render the json in laravel ?
The controller to recieve the JSON
public function productoscercanos ($lat,$long){
$subastas = Subasta::all();
$categorias = Categoria::all();
$provincias = Provincia::all();
$cercanos = User::with(array('municipio', 'subastas'))->get();
$coordA = Geotools::coordinate([$lat,$long]);
$output = [];
foreach ($cercanos as $p) {
if(count($p->subastas)>0){
$coordB = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
$distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
$dis = $distance->in('km')->haversine();
$output[$dis] = $p."<p>$dis</p>";
}
}
ksort($output);
return view('prodcercanos')->with('categorias',$categorias)->with('provincias',$provincias)->with('subastas',$output);
}
$json = (your json file);
$subasta = json_decode($json);
then you should be able to use the json as a object now.
Try array syntax in the second foreach loop.
#foreach ($subasta['subastas'] as $sub)
{{$sub}}
#endforeach
Your code is outputting exactly what is defined. First look at how the controller is building the array.
$output[$dis] = $p."<p>$dis</p>";
$p is a User model from the variable $cercanos, appending it to $dis results in it being converted into JSON and added to your output array which your view iterates and outputs.
It looks like you are trying to add the distance to the user and pass it on.
Instead use an Accessor & Mutator to add an extra attribute to your model then pass on the $cercanos list to the view, from there you can render using a for each and grab the value.
#foreach($cercanos as $c)
{{ $c->username }} {{ $c->dis }}
#endforeach
Update
Once you have added your accessor and mutator you will be able to sort using Collections built in method.
$cercanos->sortBy('dis');