Laravel template with function? - php

I'm currently in the process of modernizing a legacy codebase and using Laravel.
The current infrastructure does something like this to print a value:
while($row = mysql_fetch_array($query) {
echo $row['value'];
}
All good... Easy to do in Laravel.
Except, it then does something like this...
while($row = mysql_fetch_array($query) {
echo $row['value'];
echo getValue($row['another_value']);
}
It calls another function to fetch the value each time in the loop and print the right value.
How can I replicate this or do the same thing without having a function in Laravel?
My code looks like this (blade's templating):
#foreach ($values as $value)
<td> {{ $value->value }} </td>
#endforeach
And obviously, this doesn't work:
#foreach ($values as $value)
<td> getValue({{ $value->value }}) </td>
#endforeach

The following code:
#foreach ($values as $value)
<td> getValue({{ $value->value }}) </td>
#endforeach
Should be like this:
#foreach ($values as $value)
<td>{{ getValue($value->value) }}</td>
#endforeach
Actually {{ }} print out anything (String) between those curly brackets, so {{ getValue($value->value) }} will be replaced with <?php echo getValue($value->value) ?>. Make sure that, your function returns a string value.

Related

how to add index in laravel blade html attribute while calling collection

I am calling categories collection from controller and displaying in the blade in foreach loops
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="1">{{ $subcategory->name }}</a>
#endforeach
#endforeach
I need to add index numbers generated in the loop from 1 in data-column value
data-column="1"
data-column="2"
data-column="3"
so on....in
For doing this you need to make a variable for counting after that you should pass that variable to view like below.
I am inside a method
public function getSingle($slug){
$category= Post::where('slug','=',$slug)->first();
if ($post != null) {
$counter = 0;
return view('blog.single')->withCategories($category)->withCounter($counter);
} else {
return view('error.error404');
}
}
After that you should access that Counter variable in view like below
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{$counter++}}">{{ $subcategory->name }}</a>
#endforeach
#endforeach
The classic for will do
#foreach ($categories as $category)
#for ($i = 0; $i < count($category->subcategories); $i++)
<a class="a.toggle-vis" data-column="{{$i}}">{{ $category->subcategories[$i]->name }}</a>
#endfor
#endforeach
For a shorter one, I think, we can do something like this. A little bit dirty in view but in the small snippet, it should be okay.
{{ !($index = 1) }}
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{ $index++ }}">{{ $subcategory->name }}</a>
#endforeach
#endforeach
Use this simple solution (Laravel method):
$loop->iteration The current loop iteration (starts at 1).
It will automatically increment, in every loop iteration.
Check docs:
The Loop Variable

Getting the position (index) of an object in foreach?

I have a simple foreach block in my view, like below.
#foreach ($teams as $key => $team)
{{ str_ordinal($key + 1) }}
#endforeach
Right now I'm displaying the key, although it isn't exactly accurate. Here's an image:
How can I display the actual position of the current iteration? I order by my teams collection but I'm not sure how I get the position of the current interation in that loop?
You can use $loop->index to get the index. Check its docs. For instance:
#foreach ($teams as $team)
{{ $loop->index }}
#endforeach
Will display 0,1,2,3,4... until the last element position.
You can apply array_values to your data before passing to template:
array_values($teams);
Or, according to this https://laravel.com/docs/5.6/blade#the-loop-variable, you can use special $loop variable. I suppose you need $loop->iteration property (it starts with 1) or $loop->index (starts with 0):
#foreach ($teams as $key => $team)
{{ $loop->iteration }}
#endforeach
#foreach($teams as $team)
<tr>
<td>{{ $loop->index+1}}</td>
<td>{{ $team->name}}</td>
<td>{{ $team->caption}}</td>
<td>{{ $team->address}}</td>
</tr>
#endforeach
Use a for loop instead of a foreach. You will get them in order.
$count = count($teams) ;
for($i=1;$i<=$count;$i++) {
// your code here using $i as the position
}
In Controller
foreach ($partners as $key => $partner) {
$data['id'] = $key + 1;
}
I have solved the same issue with the combination of built in loop variable and php directive
*this is wrong* You cannot use it directly in double curly braces
{{ $loop->index }}
Instead use it like this,
#foreach ($users as $user)
#php($count= $loop->index + 1)
<tr>
<th>{{ $count }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->created_at }}</td>
</tr>
#endforeach
Though $loop variable is available inside foreach, you cannot use it inside the curly braces in blade template.
use this only it works fine {{$key+1}}

Laravel foreach multiple data

This is how I wish to be
Actual
Status gets printed 3 times
I return this objects from my controller:
return view('ViewTicket') ->with('tickets', $tickets)
->with('user', $user)
->with('priority', $priority)
->with('status', $status)
->with('type', $type);
However I want to print the respective fields like in my view:
#foreach ($tickets as $t)
<tr>
<td> {{$t->id}} </td>
#foreach ($user as $u)
#if($t->user_id==$u->Id)
<td>{{ $u->UserName }}</td>
#endif
#endforeach
Even this doesnt solve my problem.Is there any way to avoid the loop inside the loop to get these data?The goal is to get respective fields for each ticket
If I dd($user) it returns 3 values okay
when I loop in my view it displays 9 values,which means it loops 3 times the lements
Thanks in Advance
ASSUMPTIONS
$tickets is a collection of ticket objects.
$user is a collection of user objects.
CODE
#foreach ($tickets as $t)
<tr>
#foreach ($user as $u)
#if($t->user_id == $u->Id)
<td> {{$t->id}} </td>
<td>{{ $u->UserName }}</td>
#endif
#endforeach
</tr>
#endforeach

foreach in blade template not working correctly

I'm having issues on displaying my data from foreach loop. I have 400+ thumbs on my database but laravel doesn't not work correctly, and my footer template didn't display too. I will put my code below.
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
myfooter code goes here.
from my controllers
$data['thumbs'] = thumb::all();
return View('tubetour/home',$data);
but when I tried to var_dump or return the value of thumbs on my controller
it displays all my 400+ data.
$data['thumbs'] = thumb::all();
return $data['thumbs'];
You need to pass an associative array as a second argument to the view function:
// Controller
$thumbs = Thumb::all();
return \View::make('tubetour.home', ['thumbs' => $thumbs]);
// View
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Edit: if you are using laravel 4 you will need to use View::make()
If Thumb is an Eloquent model, then the Thumb::all() will return an Eloquent collection, not an array. In that case you have to update your blade template like so:
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Hope this solve your issue.
UPDATE
Pass the $thumbs as an array and display it as table.
Update your controller like this:
$data['thumbs'] = thumb::all()->toArray();
return View('tubetour/home', $data);
And your view like this, see how many rows being displayed.
<table>
<thead>
<tr>Id</tr>
<tr>Name</tr>
<td>Desc</td>
<td>Place</td>
</thead>
<tbody>
#for ($i = 0; $i < count($thumbs); $i++)
<tr>
<td>{{ $i }}</td>
<td>{{ $thumbs[$i]['name'] }}</td>
<td>{{ $thumbs[$i]['desc'] }}</td>
<td>{{ $thumbs[$i]['place'] }}</td>
</tr>
#endfor
</tbody>
</table>
UPDATE 2
Blade template example with bootstrap grid:
<div class="row">
#for ($i = 0; $i < count($thumbs); $i++)
<div class="col-md-4">
<img src="img/sample.jpg">
<h3>{{ $thumbs[$i]['name'] }}</h3>
{{ $thumbs[$i]['desc'] }}
</div>
#endfor
</div>
try this
#foreach($data as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
Update your controller
$data = Thumb::all();
return View::make('tubetour/home')->with("thumbs",$data)
->render();
Then your view with this:
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach

Laravel do not show category if foreach is empty

I have the following controller and models:
Appointments Controller:
if ($view === 'default') {
$appointments = Appointment::with('label')->with('status')->paginate(25);
}
if ($view === 'label') {
$appointments = Label::with('appointments')->paginate(25);
}
Appointment Model:
public function label()
{
return $this->belongsTo('App\Label');
}
Label Model:
public function appointments()
{
return $this->hasMany('App\Appointment');
}
In my "default" view, the following is displayed:
And in my "label" view, the following is displayed:
What I want to accomplish is, when a label has no appointments, I do not want the label to be shown at all. So, in my "label view" (check out the below image) I only want the "business" and "personal" label (and it's appointments as shown in image) to be displayed, and all the other labels shouldn't be displayed.
In my views I am using simply foreach loops. Any pointers in the right direction?
My view (simple):
#if ($view === 'label')
#foreach ($appointments as $appointment)
<table>
<tr>
<th><p>{{ $appointment->label }}</p></th>
</tr>
#foreach ($appointment->appointments as $label)
<tr>
<td>{{ $label->appointment }}</td>
</tr>
#endforeach
</table>
#foreach ($appointments as $appointment)
#endif
Try this:
You can achieve this by checking for non empty appointments. Here we would check for the negative case of empty () method.
View (blade)
#if ($view === 'label')
#foreach ($appointments as $appointment)
<table>
#foreach ($appointment->appointments as $key=> $label)
#if(!empty($label))
#($key == 0)
<tr>
<th><p>{{ $appointment->label }}</p> </th>
</tr>
#endif
<tr>
<td>{{ $label->appointment }}</td>
</tr>
#endif
#endforeach
</table>
#endforeach
#endif
Hope this is helpful.
You need to check the length of the array before you write the label. So here you'd make sure that $appointment->appointments count is greater than 0.
#if ($view === 'label')
#foreach ($appointments as $appointment)
#if (count($appointment->appointments) > 0)
<table>
<tr>
<th><p>{{ $appointment->label }}</p></th>
</tr>
#foreach ($appointment->appointments as $label)
<tr>
<td>{{ $label->appointment }}</td>
</tr>
#endforeach
</table>
#endif
#foreach ($appointments as $appointment)
#endif

Categories