Laravel take first 5 foreach - php

I trying to take out 5 users from DB by points.
BLADE:
#foreach ($users as $user)
<li>{!! $user->username !!} {!! $user->ELO_points !!}</li>
#endforeach
</div>
But i need just first 5 and first 3 with custom text content, example:
USER1 - CUSTOM CONTENT TEXT
USER2 - CUSTOM CONTENT TEXT
USER3 - CUSTOM CONTENT TEXT
USER4
USER5
I have been tried with #if ($loop->first)This is the first iteration.#endif
But loop take out just first and last one yeah?

You can use $loop->index in your loop :
#foreach ($users as $user)
<li><a href="/players/{!! $user->slug !!}">
{!! $user->username !!} {!! $user->ELO_points !!}
{!! $loop->index <=3 ? 'custom content text' : '' !!}
</a></li>
#endforeach

You can use the take way of doing it. Example
IN CONTROLLER (To make sure you only get the 5, user orderBy to either get the first or the last.)
$users = Users::all()->take(5)->get();
IN VIEW: (To make sure the 3 first get the custom content text
#foreach ($users as $user)
<li><a href="/players/{{ $user->slug }}">
{{ $user->username }} {{ $user->ELO_points }}
{{ $loop->index <=3 ? 'custom content text' : '' }}
</a></li>
#endforeach

Related

Is this possible to paginate laravel with condition?

I want to have pagination in single post page, datas comes from "contents" table. But i want to have pagination when catch spesific word (Section) as a title go to next page in same post.
Is this possible to make it with Laravel 5.4 .
Example :
Section 1 ( this is title)
text text text text text text
( next page > I want to add next page and it will go Section 2 page)
Section 2
text text text text text text
( next page >)
my Post.php
public function contents()
{
return $this->hasMany(Content::class);
}
blade view :
#if($post->contents)
#foreach ($post->contents as $content)
#if ($content->type == "header")
<h4>{{ $content->body }}</h4>
#endif
#if ($content->type == "text")
<p>{{ $content->body }}</p>
#endif
#endforeach
#endif
For pagination use paginate() inside your model.
public function contents()
{
return $this->hasMany(Content::class)->paginate(1);
}
View file
#if($post->contents)
#foreach ($post->contents() as $content)
#if ($content->type == "header")
<h4>{{ $content->body }}</h4>
#endif
#if ($content->type == "text")
<p>{{ $content->body }}</p>
#endif
#endforeach
{{ $post->contents()->links() }}
#endif

Laravel nl2br not getting foreach parameters properly

So i am currently working with nl2br. I don't know whether this is a bug, or a wrong way to doing things from my side but i encounter this. First of all, here's the snippet :
#foreach($dataList as $data)
<div class="productDesc">
{!! nl2br(e($data->product->description)) !!}
</div>
#endforeach
When i run this, the output is only the description of the first product. I initially thought there's something wrong with my code but when i do a debug like this :
#foreach($dataList as $data)
{{ $data->id }}
<div class="productDesc">
{{ $data->id }}
{!! nl2br(e($data->product->description)) !!}
</div>
{{ $data->id }}
#endforeach
The result in the 2nd row is :
2
1 This is a description for 1st product
2
As you can see, it somehow ignore the forwhile loop parameter. Can someone inform whether there's a solution for this or am i just code it wrongly ?

How to display something only for the first item from the collection in Laravel Blade template

I have a #foreach loop in the Blade template and need to apply special formatting to the first item in the collection. How do I add a conditional to check if this is the first item?
#foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
#endforeach`
Laravel 5.3 provides a $loop variable in foreach loops.
#foreach ($users as $user)
#if ($loop->first)
This is the first iteration.
#endif
#if ($loop->last)
This is the last iteration.
#endif
<p>This is user {{ $user->id }}</p>
#endforeach
Docs: https://laravel.com/docs/5.3/blade#the-loop-variable
SoHo,
The quickest way is to compare the current element with the first element in the array:
#foreach($items as $item)
#if ($item == reset($items )) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
Or otherwise, if it's not an associative array, you could check the index value as per the answer above - but that wouldn't work if the array is associative.
Just take the key value
#foreach($items as $index => $item)
#if($index == 0)
...
#endif
<h4>{{ $item->program_name }}</h4>
#endforeach
As of Laravel 7.25, Blade now includes a new #once component, so you can do it like this:
#foreach($items as $item)
#once
<h4>{{ $item->program_name }}</h4> // Displayed only once
#endonce
// ... rest of looped output
#endforeach
Laravel 7.* provides a first() helper function.
{{ $items->first()->program_name }}
*Note that I'm not sure when this was introduced. So, it may not work on earlier versions.
It is only briefly mentioned in the documentation here.
The major problem with Liam Wiltshire's answer is the performance because:
reset($items) rewind the pointer of $items collection again and again at each loop... always with then same result.
Both $item and the result of reset($item) are objects, so $item == reset($items) requires a full comparison of its attributes... demanding more processor time.
A more efficient and elegant way to do that -as Shannon suggests- is to use the Blade's $loop variable:
#foreach($items as $item)
#if ($loop->first) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
If you want to apply a special format to the first element, then maybe you could do something like (using the ternary conditional operator ?: ):
#foreach($items as $item)
<h4 {!! $loop->first ? 'class="special"': '' !!}>{{ $item->program_name }}</h4>
#endforeach
Note the use of {!! and !!} tags instead of {{ }} notation to avoid html encoding of the double quotes around of special string.
Regards.
if you need only the first element you can use #break inside your #foreach or #if.see example:
#foreach($media as $m)
#if ($m->title == $loc->title) :
<img class="card-img-top img-fluid" src="images/{{ $m->img }}">
#break
#endif
#endforeach
you can do it by this way.
collect($users )->first();
To get the first element of a collection in Laravel, you can use :
#foreach($items as $item)
#if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
#else
<h5>{{$item->program_name}}</h5>
#endif
#endforeach

Returning checked checkboxes based on pivot table

This question is regarding Laravel and PHP.
I am building a form that allows users (players) to be assigned to / de-assigned from a team using checkboxes.
Many users can belong to many teams. I have a pivot table team_user to manage the many-to-many relationship.
I am having trouble populating the checkboxes based on whether the association exists in the pivot table.
So far I have them in two separate 'bits', which you can see below:
My Controller:
$users_checked = $team->users()->get();
$users = User::all();
return View::make('team/addplayers', compact('users', 'team', 'users_checked'));
My View:
#foreach ($users_checked as $user_checked)
<p>
{{ Form::checkbox('player[]', $user_checked->id, true) }}
{{ Form::label('email', $user_checked->email) }}
</p>
#endforeach
#foreach($users as $user)
<p>
{{ Form::checkbox('player[]', $user->id ) }}
{{ Form::label('email', $user->email) }}
</p>
#endforeach
What is the most sensible way to 'combine' these into one list, where the checkbox is ticked if the association exists in the pivot, or not ticked if it doesn't?
Many thanks for any help!
The answers put me on the right track, thank you. My actual solution is below:
In my controller:
public function showAddPlayer(Team $team)
{
$users = User::all();
return View::make('team/addplayers', compact('users', 'team'));
}
In my view:
#foreach ($users as $user)
<p>
{{ Form::checkbox('player[]', $user->id, $team->users->contains($user->id)) }}
{{ Form::label('email', $user->email) }}
</p>
#endforeach
I think you may try something like this:
$teams = Team::with('users')->get();
return View::make('team/addplayers', compact('teams'));
In your view:
#foreach ($teams as $team)
#foreach ($team->users as $user)
<p>
{{ Form::checkbox(
'player[]',
$user->id,
(in_array($user->id, $team->users->fetch('id')) ? 1 : 0)
)
}}
{{ Form::label('email', $user->email) }}
</p>
#endforeach
#endforeach
{{ Form::checkbox('player[]', $user->id,in_array($user->id, $users_checked->lists('id')) ? 1 : 0 ) }}

How do I provide inline error feedback with Laravel 4 and Twitter Bootstrap 3?

I'm building a form using Laravel 4 and Twitter Bootstrap 3 and I want to error messages to appear next to the field. This is the solution that I came up with but it ends up being 15 lines of code per field.
#section('content')
<div class="container">
<h1>Edit User</h1>
{{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) }}
{{-- First Name field --}}
{{-- Start a form group. If there any errors, then highlight the field red. --}}
<div class="form-group {{ $errors->has('first_name') ? 'has-error' : '' }}">
{{-- Display the label and the field. --}}
{{ Form::label('first_name', 'First Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('first_name', NULL, array('class' => 'form-control', 'placeholder' => 'First Name')) }}
</div>
{{-- If there is an error, display any messages to the right of the field with a warning icon. --}}
#if($errors->has('first_name'))
<div class="col-sm-5">
#foreach ($errors->get('first_name') as $message)
<span class="help-block">
<span class="glyphicon glyphicon-warning-sign"></span>
{{ $message }}
</span>
#endforeach
</div>
#endif
</div>
{{-- Form buttons --}}
<div class="form-group">
{{-- Line up the buttons with the right edge of the fields. --}}
<div class="col-sm-offset-2 col-sm-5">
<div class="pull-right">
{{-- Cancel button takes user back to profile page. --}}
{{ HTML::linkRoute('users.show', 'Cancel', array($user->id), array('class' => 'btn btn-default')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
</div>
</div>
{{ Form::close() }}
</div>
#stop
This is how it appears:
I'm just starting out with both Laravel and Bootstap. I used Jeffery Way's tutorial on NetTuts to make the form and Coder's Guide's tutorial to apply the formatting.
Should I be using client-side validation or would this be considered an acceptable implementation of Laravel 4 and Bootstrap?
Thanks!
This may not be the coolest way to do this but I think it's pretty slick.
Laravel has a feature called Form::macro that allows you to sort of make reusable code snippets. You can define a macro all kinds of places but I just slapped mine in my routes.php file to get this going real quick.
Form::macro('errorMsg', function($field, $errors){
if($errors->has($field)){
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});
Then to use in a form, pass the macro your error messages:
{{ Form::label('first_name', 'First Name:') }}
{{ Form::text('first_name') }}
{{ Form::errorMsg('first_name', $errors) }}
{{-- where $errors is your Illuminate\Support\MessageBag object --}}
To get even more tech, you can use Form::objects in a Form::macro like so:
Form::macro('textError', function($field, $label, $errors){
$label_html = Form::label($field, $label);
$text_html = Form::text($field);
$msg_html = '';
if($errors->has($field)){
$msg_html.= '<span class="error">';
$msg_html.= $errors->first($field);
$msg_html.= '</span>';
}
return $label_html.$text_html.$msg_html;
});
Then you're at 1 line per input:
{{ Form::textError('first_name', 'First Name:', $errors) }}
You'd need to make other macros for password, textarea, etc. (which is why I just use the first example; it's only a couple more lines of code per input and serves all input types.)
If you wanted to style your input on error, eg. a red border, you'd probably want the second example then wrap it in your div.form-group or whatevers. Anyway, options out the wazoo.
UPDATE: An even slicker way to get errors in macros is to access them via Session::get('errors'); like so:
Form::macro('errorMsg', function($field){//yay! we don't have to pass $errors anymore
$errors = Session::get('errors');
if($errors && $errors->has($field)){//make sure $errors is not null
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});

Categories