i have live json and i want to display it on laravel blade
my controller code is :
public function index()
{
$json = json_decode(file_get_contents('link_of_json_file'),true);
return view('show' , compact('json'));
}
and blade code is :
#foreach ($json as $p)
{{ $p->name }}
#endforeach
and this erros is display:
(2/2) ErrorException
Trying to get property of non-object (View:
E:\work-landingpage\test\JSON\resources\views\show.blade.php)
you can remove the "true" to use it as object :
public function index()
{
$json = json_decode(file_get_contents('link_of_json_file'));
return view('show' , compact('json'));
}
#foreach ($json as $p)
{{ $p->name}}
#endforeach
so if you want to use it as array you can use it like:
#foreach ($json as $p)
{{ $p['name']}}
#endforeach
Related
how do I display an object name of an array that I fetched from the database in Laravel blade?
When I dump array in Laravel controller I get this "name" => "{"name":"Item 1"}". Now, how do extract Item 1 from array and display in a blade while looping using foreach.
Controller
$data = DB::table('items')
->select('name')
->where('id', $user->id)
->get();
$output = json_decode($data,true);
dd($output);
Results
"name" => "{"name":"Item 1"}
Kindly help.
You have to extract from each object separately.
Variant 1:
Controller:
$data = DB::table('items')->select('name')->where('id', $user->id)->get()
->map(function($item){
$item->name = json_decode($item->name, true);
return $item;
});
return view('some_view', ['data' => $data]);
View:
#foreach($data as $d)
<p>{{ is_array($d->name) ? $d->name['name'] : 'No Name' }}</p> {{-- Just Checking if Json is correctly decoded --}}
#endforeach
Variant 2:
Controller:
$data = DB::table('items')->select('name')->where('id', $user->id)->get();
View:
#foreach($data as $d)
#php($name = json_decode($d->name, true))
<p>{{ is_array($name) ? $name['name'] : 'No Name' }}</p> {{-- Just Checking if Json is correctly decoded --}}
#endforeach
Controller:
$dataes = DB::table('items')
->select('name')
->where('id', $user->id)
->get();
return view('viewName',compact('dataes'));
View:
#foreach($dataes as $data)
{{ $data->name }}
#endforeach
I'm trying to get data saved in json format inside database column
Data:
[
{
"option_value":"Delhi",
"optionl2_value":"\u0926\u092f\u093e\u0930\u093e\u092e \u0938\u093e\u0939\u0928\u0940",
"has_file":0,
"file_name":""
},
{
"option_value":"Panjab",
"optionl2_value":"\u0930\u093e\u0916\u0932\u0926\u093e\u0938 \u092c\u0928\u0930\u094d\u091c\u0940",
"has_file":0,
"file_name":""
}
]
and here is the code i'm using.
#if(is_array(json_decode($question->answers)))
#foreach ( json_decode($question->answers) as $value)
<span> {{ $value->option_value }}</span><br>
#endforeach
#endif
and I get the following error
> Error : Undefined property: stdClass::$option_value
How can I resolve?
This works for me:
<?php
$data = json_decode($jsondata);
?>
<ul>
#foreach($data as $value)
<li> {{ $value->city}}</li>
#endforeach
</ul>
So I know about passing variables via the controller for instance if its a query array I will do
public function index()
{
$query = Request::get('q');
if ($query) {
$users = User::where('username', 'LIKE', "%$query%")->get();
}
return view('view', compact('users'));
}
And when on the blade I will do
#if( ! empty($users))
#foreach($users as $user)
{{ $user->username }}
#endforeach
#endif
Now my question is how do I set a variable using a variable from the foreach? at the moment I am using PHP inside of the blade template file but I feel this is messy, here is what I have
#if( ! empty($users))
#foreach($users as $user)
<?php
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($user->last_online))->diffForHumans();
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
?>
{{ $user->username }}
#if ($user->last_online <= $fiveMinsAgo)
{{ $lastOnline }}
#else
Online Now
#endif
#endforeach
#endif
found a solution to my issue if anyone else is ever looking for it.
public function getLastOnlineAttribute($value)
{
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
$thirtMinsAgo = \Carbon\Carbon::now()->subMinute(30);
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
if ($value <= $fiveMinsAgo) {
echo 'Last Active: '.$lastOnline.'';
}
else {
echo 'Online Now';
}
}
Basically add this into your model for the variable (eg, if its a $user->last_online it would go into the user model) , it is called a eloquent mutator if you are ever looking for more info, https://laravel.com/docs/master/eloquent-mutators
It grabs your data for the variable for instance {{ $user->last_online }}
Note that the Underscore is transformed into a CamelCase in the function name, the output is set at $value, you can then set variables inside of the function and mould the output however you wish, then in the blade you can get rid of all the extra crap and just use {{ $user->last_online }}
In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});
I've searched for all solutions to implement pagination successfully, but nothing I've found worked. I'm new to Laravel so I have maybe only one of those basic misunderstandings.
I have created it like it is described in the current documentation. And I get the first page successfully, exactly the content i need, but when i try to use the pagination, clicking on the "next"-arrow, I get an error message:
ErrorException
Undefined variable: reviews (View: D:\Xampp\htdocs\laravel\app\views\search.blade.php)
I know what this generally means but absolutely no idea how to solve this.
This is the form in the view file:
{{ Form::open(array('url' => '/search', 'class' => 'search', 'method' =>'GET')) }}
{{ Form::text('title') }}
{{ Form::submit('Suche')}}
{{ Form::close() }}
Here is my routes configuration:
Route::any('/search', array('uses' => 'HomeController#search'));
Here is my function in the HomeController:
public function search() {
$input = Input::get('title');
if($input && $input != ''){
$games = DB::table('games')->where('name', 'LIKE', "%$input%")->get();
foreach ($games as $game) {
$reviews = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
}
return View::make('search', compact('reviews', 'input', 'games'));
}
Here is the view-code of the search.blade.php view, which displays the results:
#section('content')
<h2>Suchergebnisse</h2>
#foreach ($reviews as $review)
#foreach ($games as $game)
#if ($game->id == $review->game_id)
<h3> {{ $game->name }} </h3>
#endif
#endforeach
<p>{{ (preg_replace('/\n/i', '<br/>', $review->body)) }}</p>
#endforeach
{{ $reviews->appends(array('term' => $input))->links() }}
#stop
I thank you beforehand if someone knows why Laravel has a problem with this solution.
Edit:
I've changed the compact-statement and replaced it with an simple array, just like that:
return View::make('search', array('reviews' => $reviews, 'input' => $input, 'games' => $games));
Then I've added global $games; global $reviews; to the Controller, so the Error "Undefined variable: reviews" disappeared. Now I've got the following message, but only on page 2, page 1 works fine:
ErrorException
Invalid argument supplied for foreach() (View: D:\Xampp\htdocs\laravel\app\views\search.blade.php)
First of all you are doing this
foreach ($games as $game) {
// $reviews is being updated every time in loop
$reviews = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
So, every time there is a new value is being set to $review but it should be an array and that's why you should declare an empty array before the loop like this
$reviews = []; // or array();
foreach ($games as $game) {
$reviews[] = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
So, you'll get an array in the $review variable.
Regarding your error message Undefined variable: reviews, it's not defined and it could be because if($input && $input != '') condition doesn't match or $games got nothing, so, try to debug step by step your code, at first make sure that execution control is being entered inside if by making dd($input) statement inside if and then if it outputs anything then make sure $games is not null/false by making a dd($games) statement after the games query.
You can change the code snippet to this
$input = Input::get('title');
if($input) {
$games = DB::table('games')->where('name', 'LIKE', "%$input%")->get();
if($games) {
$reviews = []; // or array();
foreach ($games as $game) {
$reviews[] = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
return View::make('search', compact('reviews', 'input', 'games'));
}
}
// return a 404 (not found) or something like this or whatever, when nothing found