How to display specific data from array? - laravel

How can I correct display data from array. I guess it's a foreach loop, but I do not know how to bite it. I just need only header. It's in table calendars.
Thanks so much!
#foreach($list as $item)
{{ $item->header }}
#endforeach
I tried the above code but throws out an error, unknown value "header"
#foreach($results as $type => $list)
<div class="single-contact-information mb-30">
<h3>{{ $type }} </h3>
{{ $list }}
</div>
#endforeach
[{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}]
Edit:
SearchController:
public function search(Request $request)
{
$search = $request->get('search');
$results = [];
$results['calendars'] = DB::table('calendars')->where('header', 'like', '%'.$search.'%')->get();
return view('pages.search', ['results' => $results]);
}

You should try this:
[{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}]
Above value is json then use below code
$list = [{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}];
#foreach($list as $item)
{{ $item['header'] }}
#endforeach
$list = json_decode($list);
#foreach($list as $item)
{{ $item['header'] }}
#endforeach
Updated Answer
#foreach(json_decode($list) as $item)
{{ $item->header }}
#endforeach

try this one
used json_decode function here
#foreach(json_decode($list) as $item)
{{ $item['header'] }}
#endforeach

Related

How to retrieve translation strings inside a php code in laravel blade template

I am trying to use the localization retrieval of string inside of php foreach loop code in blade template in laravel 8.
Inside the foreach loop, I am trying to manipulate a value called $item['label'] and equate translate the value of it using the language localization that laravel have.
Here's my current code.
#foreach ($items as $item)
#php
$item['label'] = "{{ __($item['label']) }}"
#endphp
#endforeach
But I get an error of
ParseError
syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
In the first place, can I use a {{ __ ('string') }} or #lang('string') inside a #php in the first place?
If I can't is there any other approach for this one?
Thank you very much!
#php and #endphp is a blade syntax, and it is the same as writing:
<?php ?>
So you could do this:
<?php
echo __('profile/username');
?>
Or you can write it using a Blade template engine:
#php
echo __('profile/username');
#endphp
To print the items you could do this:
#foreach ($items as $key => $item)
{{ __($item) }}
#endforeach
Here an example with data:
#php
$items = ['engine_1' => ['label' => 'Google'], 'engine_2' => ['label' => 'Bing']];
#endphp
#foreach ($items as $key => $item)
{{ __($item['label']) }}
#endforeach
// The output will be => Google Bing
In order to save the translation of the item, remove the "{{ }}" and use the key in order to detect on which index to apply the changes, like the following:
#foreach ($items as $key => $item)
#php
$items[$key]['label'] = __($item['label'])
#endphp
#endforeach
Notice what #Nurbek Boymurodov wrote to you, you need to use the $key, because doing something like this will not override the data within a foreach loop:
#foreach ($items as $key => $item)
#php
$item['label'] = __($item['label']); // Wrong way of overriding data
#endphp
#endforeach
while using foreach you cant change its value here try this this will work if $items is array not stdClass
#foreach ($items as $key => $item)
#php
$items[$key]['label'] = __($item['label']);
#endphp
#endforeach
Thanks, #Nurbek Boymurodov!
It was your comment that answered my question.
Here's the code right now:
#foreach ($items as $item)
#php
$item['label'] = __($item['label']);
#endphp
//other codes where I used the manipulated $item['label']
#endforeach
by just deleting the {{ }} I've manipulated the value that I want, Thank you!

View is not getting anything from the controller

Can anyone tell me why this will not return show.blade.php data?
ROUTE
Route::resource('news', 'NewsController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]);
MODEL
public function categories()
{
return $this->belongsToMany(ContentCategory::class);
}
public function tags()
{
return $this->belongsToMany(ContentTag::class);
}
CONTROLLER
public function show(News $news)
{
$news->load('categories', 'tags', 'product_press_releases', 'section');
return view('site.news.show', compact('news'));
}
VIEW show.blade.php
#section('content')
{{ $news->title ?? '' }}
{{ $news->id ?? '' }}
#foreach($news->categories as $key => $category)
<span class="label label-info">{{ $category->name }}</span>
#endforeach
#endcontent
For the life of me I cannot get why no data is being returned. I do these all the time and never ran into this.
I believe that your are not extending it to app.blade.php.
Add - #extends('YOUR_APP_LINK').
In your case -
#extends('YOUR_APP_LINK')
#section('content')
{{ $news->title ?? '' }}
{{ $news->id ?? '' }}
#foreach($news->categories as $key => $category)
<span class="label label-info">{{ $category->name }}</span>
#endforeach
#endcontent
Hope this will help you.

Use "where" and "limit" to child in #foreach

I want to display all user's profile into views and they posts. It's pretty simple:
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#endforeach
#endforeach
But I want to display only the latests posts (->orderBy('created_at', 'desc')->limit(4) ) and only accepted posts (->where('accept', 1)). How can I do that?
You already have what you need. You just need to put it all together.
#foreach($profile->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get() as $post)
I would consider creating a query scope on your profile model. That way you can do something like $profile->latestPosts.
Or you can use the relationship to return exactly what you need.
public function latestPosts() {
return $this->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get();
}
Then you could use it as:
#foreach($profile->latestPosts() as $post)
{{$post->title}}
#endforeach
A better solution would be to lazy load the posts you need when loading the profiles in the controller.
$profile = Profile::with(['posts' => function ($post) {
$post->where('accept', 1)->orderBy('created_at', 'desc')->limit(4);
}])->limit(10)->get();
then in the blade you can do the same as before
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#endforeach
#endforeach
if you want to use a scope for latestAccepted, you can on the Post model
class Post extends Model
{
public function scopeLatestAccepted($query)
{
return $query->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)
}
}
Then lazy load it
$profile = Profile::with(['posts' => function ($post) {
$post->latestAccepted();
}])->limit(10)->get();
what you have to do is pretty simple.
create table users
create table post
create a relationships between the 2 tables
write you code in controller to join the table and query all the users post based on his/her username or password
see sample screenshot for table relationships
//Controller
Public function ViewPost(){
$data['data']=DB::table('useratable')
->where('useratable.username','=', $uname)
->where('useratable.password','<=',$pwd)
->leftjoin('posttable', 'useratable.idusertable', '=', 'posttable.userid')
->orderby('posttable.idposttable','desc')
->get();
}
//Route
Route::get('/view-post','YourController#ViewPost')
//view
#foreach($data as $r)
{{ $r->fullname}} <br>
{{ $r->email}} <br>
{{ $r->topic }} <br>
{{ $r->content }} <br>
{{ $r->datetime}} <br>
...
#endforeach
You need some codes like it on controller:
$profiles = Profile::with(['posts' => function ($query) {
$query->where('accept', 1)
->orderBy('created_at', 'desc');
}])->get();
And add this one to blade file:
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#if ($loop->iteration == 4)
#break
#endif
#endforeach
#endforeach

Laravel issue- "Trying to get property of non-object"

Controller :
$args = array();
$args['name'] = "Robin";
$args['email'] = "asdasd#asdasd.net";
$clientpayments = Payments::getPaymentByClient($id);
$args['activity'] = $clientpayments;
return view('clients.show',["args" => $args]);
View:
{{ $args->name }}
{{ $args->email }}
#if (isset($args['activity']))
#foreach ($args['activity'] as $act)
{{$act->job_name}}
#endforeach
#endif;
So what the issue is is that $activity loop works fine but the $name and $email is returning a non-object error... Any ideas to where I'm going wrong?
Thanks!
Since you're using an array, change this:
{{ $args->name }}
{{ $args->email }}
To:
{{ $args['name'] }}
{{ $args['email'] }}
You are trying to access an object value, but you are sending an array to your view.
$payments = Payments::getPaymentByClient($id);
$args = array([
'name' => 'Robin',
'email' => 'asdasd#asdasd.net',
'activity' => $payments, // Expecting a collection
]);
return view('clients.show', [
"args" => (object) $args // Cast into an object
]);
Blade template (if you have an object)
{{ $args->name }}
{{ $args->email }}
// If your activity is a collection
#foreach ($args->activity as $act)
{{ $act->job_name }}
#endforeach
Blade template (if you have an array)
{{ $args['name'] }}
{{ $args['email'] }}
// If your activity is a collection
#foreach ($args['activity'] as $act)
{{ $act->job_name }}
#endforeach
Got it.
A silly mistake, but I'm just learning Laravel. I was including $args in the View rather than just $name, $email and $activity which worked perfectly.
Thanks anyway.

Laravel 4 - Enumerating #foreach

I want to enumerate some content in a #foreach. I need something like:
1 - First data
2 - Second data
...
I've displayed the data using a #foreach, but I need to enumerate it. I've tried with #for, combining with #foreach, but it hasn't worked for my... Does anybody know how to do it?
Thank you in advance!!
Assuming the array keys are not the index you want to enumerate, you can do this:
#for ($i = 0; $i < count($data); $i++)
{{ $i }} - {{ $data[$i]->field }}
#endfor
If you can use the array key for enumeration, you can do this:
#foreach ($data as $key => $value)
{{ $key }} - {{ $value->field }}
#endforeach
<?php $i = 1; ?>
#foreach ($collection as $item)
<p>{{ $i }} - {{ $item->property }}</p>
<?php $i++; ?>
#endforeach

Resources