I am trying to implement a conditional operator on a value returned from controller to create some custom view.
front.blade
#if({{count($users)}} <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
<h3> total number of rows less than or equal to 5 </h3>
#endif
controller
$users = User::all();
return view('front', [ 'users'=>$users]);
and the error is
syntax error, unexpected '<'(View: \resources\views\front.blade.php)
Tried all permutation combination of putting the condition within {{ }} or quoting the operator or the constant value 5 the error remains same. I am new to laravel and this might be a fundamental mistake in regards to laravel or php.
Just remove {{ and }}, they're not needed besides a Blade directive (#ifin this case)
You need to remove the {{ }} inside the if condition.
Like this.
#if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
<h3> total number of rows less than or equal to 5 </h3>
#endif
first you need to understand when you need to use curly braces.when you display your data in blade file you need to use curly braces. like
Hello, {{ $name }}.
You may construct if statements using the #if, #elseif, #else, and #endif directives. These directives function identically to their PHP counterparts:
#if (count($records) === 1)
I have one record!
#elseif (count($records) > 1)
I have multiple records!
#else
I don't have any records!
#endif
Your Solution
#if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 -->
<h3> total number of rows less than or equal to 5 </h3>
#endif
for details go into laravel documentation https://laravel.com/docs/7.x/blade#if-statements
In Controller change your code like this -
$users = User::all();
return view('front', compact('users'));
Blade file code-
#if(count($users) <= 5) <!-- if total number of rows in users table is less than or equal to 5 --><h3> total number of rows less than or equal to 5 </h3>#endif
Related
How to print limited data with FOREACH
I have 10 data in db but, i want to print only first 3 data with foreach.
Also i tried and used array_slice() method, but next i got some errors.
Thank you!
#foreach($products as $_product)
//there is Html code... with variables
#foreach
I tried : #foreach(array_slice($products, 0, 2) as $_product). and i got:
array_slice() expects parameter 1 to be array, object given.
You can use limit(3) in your eloquent or take(3)
Or if you need to make it in blade use $loop variable
Like this
#if($loop->iteration <=3)
#continue
Or in your controller
Product::limit(3)->get();
Product::take(3)->get();
If u use it in controller there will be no need to check in your blade view
Just use the #break; statement once you've printed however many you want - it will jump you out of the foreach loop.
so something quick i can think of this:
#foreach($products as $_product)
//there is Html code... with variables
#if($loop->iteration == 3) //Thanks to the response of #MohammedAktaa
#break
#endif
#foreach
Although I think it should be best to limit the results from the query to the database.
Ordering, Grouping, Limit, & Offset
First, my apologies if the issue has been resolved. I read a lot of similar posts, but not quite the right one for my case.
I am setting up a simple project in Laravel 5.8. I want to create a simple bookstore and I need a book to have multiple authors so each title is followed by the author, or authors - if many - separated by commas and the last one by the word 'and'.
I have set up two Models, 'Author' and 'Book' and their respective tables, as well as a pivot table since they are in a relation belongsToMany. Everything works like a charm, I get my results as expected. However, I cannot get to format the results as I need. In the case of multiple authors, I always get an extra comma in the end. Since I cannot get the commas right I haven't yet tried to add the last 'and' in the case of the last author.
In the case of a single author the solution is easy, I just use a conditional.
However in the case of multiple authors, thing get complicated.
The most popular method to similar problems was the use of implode() in various similar ways. The problem with this method is since Eloquent is using its internal logic to perform the query, when I loop through 'books', there is no author column, just a reference to the pivot table. In addition, the authors' include first name and last name in different columns. So, when I try to manually create an 'implodable()' array by fetching the respective data otherwise, I get double the item size, since each name consists of the first name and theist name. And on top of that, the whole thing runs inside a double loop, making things even more complicated for me.
I am sure there is a simple way around this.
This is a sample of my blade code as of now. Of course the conditionals should be rearranged accordingly when the problem will be solved, to implement the 'and' case:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#if (count($book->author) == 1)
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
#endforeach
#else
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
{{-- print a comma here if there are other names, or an 'and' if it the last one. Problem seems that it needs to be solved outside the conditional, but how? --}}
#endforeach
#endif
</li>
#endforeach
</ul>
My DB structure:
'authors': 'id', 'last_name', 'first_name','created_at', 'updated_at'
'books': 'id', 'title', 'created_at', 'updated_at'
'author_book': 'id', 'author_id', 'book_id','created_at', 'updated_at'
Expected result:
Title 1, by Author 1
Title 2, by Author 1 and 2
Title 3, by Author 1, 2 and 3
Actual Result:
Title 1, by Author 1
Title 2, by Author 1 and 2 and
Title 3, by Author 1 and 2 and 3 and
If you didn't need the "and" mechanism, then implode with comma would do the job. For "and" mechanism use below code:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#for ($i = 0; $i < count($book->author); $i++)
{{ $book->author[$i]->last_name }}
{{ $book->author[$i]->first_name }}
#if ($i == count($book->author) - 2)
and
#endif
#if ($i < count($book->author) - 2)
,
#endif
#endfor
</li>
#endforeach
</ul>
added non-breaking-space   wherever necessary to not get them linked to each other
Delete #if (count($book->author) == 1), if you use foreach inside.
You can't use #else, when before you close condition with #endif.
This #else has wrong construction, use #elseif instead.
If you want check authors count and show extra value, do it inside foreach with $book->author()->count().
What relation u have for book -> author? One book can have many authors or not?
Just display implode(', ', $book->author), based on your actual result you don't need to do complicated checking if/else anymore.
#foreach ($books as $book)
<li>{{ $book->title }} by {{print implode(', ', $book->author)}}</li>
#endforeach
I am using blade for the first time, and i need to change the styling of this div element depending on how many properties are available. I need to write an if statement which hides the div if equal or less than one and add a different class if equal to 2.
how would i write this using blade or php?
#if (isset($participatingProperties) && !empty($participatingProperties) && is_array($participatingProperties))
<?php $i = 0; ?>
#foreach ($participatingProperties as $key => $property)
#if ($i++ % 3 === 0)
<div class="item item2 {{ $i < 3 ? 'active' : '' }}">
#endif
What I understand is :
You have a $participatingProperties array and one div to print.
When it has 0 or 1 element, nothing happens.
When it has 2 elements, the div prints with a specific style.
When it has 3 or more elements, the div prints with another style.
(No rule for more than 3 elements).
I would keep it simple with count :
#php($count = count($participatingProperties))
#if ($count > 1)
<div
class="{!! ($count == 2) ? 'class-2' : 'class-3-or-more' !!}"
>
div content
</div>
#endif
If you don't need a specific style for every amount, it's even simpler :
#if (count($participatingProperties) > 1)
<div class="myclass">
div content
</div>
#endif
Using both empty and isset is redundant. And I think you should not have to check if $participatingProperties is an array, instead make sure it always is in your backend. If you return at least an empty array, count will return 0.
I have two tables.
contenttype
content
contenttype returns me list of content types and I show them on page with foreach. e.g. Ambulance service, Blood Bank , clinic etc. as shown in snapshot.
At the same time I am fetching total number of contents of each type from another table(contents).
I was successful to get total number of contents of each type and show on the blade with foreach.
But situation is I want to show the number of contents on every content type.
Like this
Ambulance sevice 8,
Blood Bank 7,
Clinic 4.
My controller method is:
public function index()
{
if (Gate::allows('edit-content', auth()->user())) {
// below line returns list of content type e.g Ambulance service
$type = DB::table('contenttype')->distinct('label')->orderBy('label', 'asc')->paginate(10);
//below line counts the number of each content type e.g. Ambulance service 10.
$count = Content::selectRaw('type, count(*)total')->groupBy('type')->get();
return view('admin.content_listing', compact('type', 'count'));
} else {
abort(403, "Unauthorized");
}
}
This is blade code:
#foreach ($count as $c)
<span class="label label-danger">{{ $c->total }} </span>
#endforeach
This red number list is output:
#foreach ($type as $t)
<div class="list-group-item">
<a href="{{ route('content.type.listing', $t->type ) }}" > {{ $t->label }}
<span class=" pull-right glyphicon glyphicon-search"></span></a>
<span class="col-md-1 glyphicon glyphicon-plus-sign"></span>
</div>
#endforeach
Output is:
If I place above loop in second loop then Of course it will become nested loop that I don't want.
I need to show Ambulance 8,
Beauty clinic 8,
Blood Bank 1,
etc.
If anybody knows the solution kindly share it!
I have tried different ways but no success.
Rather than creating two queries and attempting to combine their results in the view, have you tried performing a join in a single query? Making certain assumptions about your column names and leaving aside the pagination, the actual SQL would be something akin to:
SELECT contenttype.*, count(content.id) FROM contenttype LEFT JOIN content ON contenttype.id = content.type GROUP BY contenttype.label ORDER BY contenttype.label ASC;
The code necessary to implement this query with Laravel's query builder functionality is pretty well documented in the documentation.
I'm trying to display search results count in the result page in Drupal 8, I want to display something like: 23 results for search_word.
I'm using the default Drupal search, and item-list--search-results.html.twig as the template file to display the results, but I can't find the search result count in the available variables, any idea how can find this value?
There is no variable for results count in Drupal 8.
1) Add this variable using the following code (add this code to MYTHEME.theme):
function MYTHEME_preprocess_item_list(&$variables) {
$total = null;
// get the total number of results from the $GLOBALS
if(isset($GLOBALS['pager_total_items'])){
$total = $GLOBALS['pager_total_items'][0];
}
$variables['count_items'] = $total;
}
2) Then you can use {{ count_items }} in item-list--search-results.html.twig:
<div> {{ count_items }} results for search_word </div>
The default way the item-list file works is to loop through and array called items so you could do something like
<div> {{ items|length }} results printed </div>
Source