whenever I run a loop it seems to turn my object null after - laravel

I have never encountered this before. In Laravel 8, every time I iterate through a collection, it becomes null after.
Example:
$loops = Loops::get();
inside of loops I have
public function loopNotifications()
{
return $this->hasMany(LoopNotifications::class, 'loop_id', 'id');
}
#if($loop->loopNotifications->count())
#foreach($loop->loopNotifications as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!!$loopNotification->convertToReadable()!!}
</div>
</li>
#endforeach
#endif
Before I run this I dd() the loop, and it's all there
After I run the same dd() and it's null. This is happening to every single foreach I run. I started to write for statements just to get past this, but at this point It's frustrating to write all the extra code.
Has anyone had this issue.

Don't use $loop as a variable in blade.
Laravel uses this variable name to give you insights about the loop itself as you were guessing correctly.
Renaming the variable and try again.
Also on a sidenote you could use the ?? operator instead of putting the whole inside a #if block: (considering you named $loop to $l)
#foreach($l->loopNotifications??[] as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!!$loopNotification->convertToReadable()!!}
</div>
</li>
#endforeach
This fallsback to an empty array if $loop->loopNotifications is null. It's not required, yours works as well, but IMHO it's cleaner.

Related

Laravel - Element displaying twice while looping inside a condition

This is the example while looping
despite having a condition and relation many too many it seems that the case
#foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)
#if (\App\Document::where('id',$item->id_document)->get())
<a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download" > Telecharger </a>
#endif
#endforeach
in the above snippet
#foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)
#if (\App\Document::where('id',$item->id_document)->get())
<a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download" > Telecharger </a>
#endif
#endforeach
code is absolutely fine, but there might be the possibility, you are running with duplicate data, you can use this also.
\App\ClientDocument::where('id_client', $clients->id)->distinct('id_client')->get()
and instead of using #if (\App\Document::where('id',$item->id_document)->get())
you can use
#if (\App\Document::where('id',$item->id_document)->firstOrFail())
#if (\App\Document::where('id',$item->id_document)->count())
That's it.
first you shouldn't loading data inside blade files
do it inside controller function
then you should create relationship inside ClientDocument model name document
and in your blade you can do that
$item->document
or whatever you want

How do I use a row count in an #if in a Laravel view?

I am brand new to Laravel and I'm running Version 6.
I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.
My MySQL table is called diary_entries and various users of the system will contribute zero to n rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.
I think I want to construct an #if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.
The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.
Here was the guess that seemed most logical to me:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1> Sleep Diary </h1>
</div>
<div>
<h3>{{Auth::user()->name }}</h3>
</div>
<div>
#if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))
<p>
<a class="btn btn-primary"> View / edit existing sleep diary entries </a>
</p>
#endif
</div>
<div>
<p>
<a class="btn btn-primary" href="/diaryEntries"> Create a new sleep diary entry </a>
</div>
</div>
#endsection
This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?
EDIT
I've imitated Sehdev's suggestion but I get this error:
$count is undefined
Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}
Here is my welcome view:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1>Sleep Diary</h1>
</div>
<div>
<h3>{{ Auth::user()->name }}</h3>
</div>
<div>
#if ($count) > 0))
<p>
<a class="btn btn-primary">View/edit existing sleep diary entries</a>
</p>
#endif
</div>
<div>
<p><a class="btn btn-primary" href="/diaryEntries">Create a new sleep diary entry</a>
</div>
</div>
#endsection
And this is the relevant function from DiaryEntryController:
public function countEntriesOneUser()
{
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
view("welcome", compact("count"));
}
Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to
view("welcome", $count);
but that produced the same error.
Try this,
#php
$count=\App\DiaryEntry::where('client', Auth::user()->name)->count();
#endphp
#if($count>1)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
Using App\DiaryEntry::select('*')->where('client', Auth::user()->name) directly on your blade template is a bad practise.
You can execute your question in your controllers method and then pass the result on your view file
Your function
function test(){
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count(); // get the total no of records using count
view("index", compact("count")) // pass your count variable here
}
then you can directly use $count in your #if condition
Your blade template
<div>
#if ($count > 0)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
</div>

How can I filter the data of foreach?

I have this design:
I need to say: last post that I add it put it in the head of design then other put them down.
My shut :) Html and foreach code:
#if ($user->projects->count() > 0)
<section class="latest section shadow-sm">
<h1>Projects</h1>
<div class="section-inner">
#foreach ($user->projects->sortByDesc('id')->take(1) as $project)
<div class="item featured text-center ">
// head post
</div>
#endforeach
#foreach ($projects_last->sortByDesc('id') as $project)
<div class="item row">
// other post
</div>
#endforeach
</div><!--//section-inner-->
</section><!--//section-->
#endif
Code of controller for $projects_last:
$projects_last = $user->projects;
$projects_last->pop();
return view('frontend.user_profile',compact('user','projects_last'));
I have the problem with when I say if the #if ($user->projects->count() > 0) do not show any thing but still show me the <h1>Projects</h1> even it is empty!
And if you have any suggest to making my code better pls do it with thankful :)
To iterate Collections you have to get them. So you have to use get() to get the results.
...
#foreach ($user->projects->sortByDesc('id')->take(1)->get() as $project)
...
and
...
#foreach ($projects_last->sortByDesc('id')->get() as $project)
...
You can see here the documentation: Laravel query documentation
Note: if you want to get just one element in your first foreach loop you can use first() instead of take(1). You code will be like that:
#php($first_project = $user->projects->sortByDesc('id')->first())
#if (!is_null($first_project))
// Use $first_project as $project variable
#enif

I want to count in if statement in foreach loop laravel 5.6

As I am new to Laravel so facing this problem and tried it in other ways but it is not working.
Here my blade file
products.blade.php
#foreach($products as $product)
<div class="women">
<h6>{{$product->title}}</h6>
<span class="size">XL / XXL / S </span>
<p ><em class="item_price">Rs.{{$product->price}}</em></p>
</div>
#if(count($product) == 3)
<div class="clearfix"></div>
#endif
#endforeach
Why this is not working
#if(count($product) == 3)
<div class="clearfix"></div>
#endif
Or how can I count the product in iteration and compare the count number in if statement?
You can use loop variable like this.
Instead of:
#if(count($product) == 3)
<div class="clearfix"></div>
#endif
you should use:
#if($loop->iteration == 3)
<div class="clearfix"></div>
#endif
But it's quite possible that you might need it after every 3 elements (3, 6, 9 and so on), so maybe better solution would be:
#if($loop->iteration % 3 == 0)
<div class="clearfix"></div>
#endif
You example didn't work because $product is just an object so count($product) will not have expected value. Also if you used count($products) (notice trailing s) it won't work because count of products is the same in each loop iteration.
If you have more or less than 3 products, your if statement is never going to show. What you're looking for is the third item in the products array, which you can do like this:
#foreach($products as $key => $product)
<div class="women">
<h6>{{$product->title}}</h6>
<span class="size">XL / XXL / S </span>
<p><em class="item_price">Rs.{{$product->price}}</em></p>
</div>
#if($key == 2)
<div class="clearfix"></div>
#endif
#endforeach
To get the index of the loop, use
#foreach ($athletes as $key=>$athlete)
// Some html goes here
{ { ++$key } }
#endforeach
add if condition to key
let me know how it goes
The array count will always be the same, inside or outside of the loop.
If you want to make a decision based on the current iteration, ex. "on every third product put a clearfix div", then apply the condition to the key if the key is numeric.
Blade provides a loop variable with an iteration property (starts at 1) to help with this, see here https://laravel.com/docs/5.6/blade#the-loop-variable
Example for every third product:
#foreach($products as $product)
...
#if ($loop->$loop->iteration%3 == 0)
<div class="clearfix"></div>
#endif
...
#endforeach
Example for the third product only:
#if ($loop->$loop->iteration == 3)
<div class="clearfix"></div>
#endif

Laravel included template is not parsing / running foreach loop

I have included a couple of files.
my home.blade.php has the following:
#include('includes.header')
my header.blade.php in includes folder has the following
#include('elements.pendingTasksLi', array('tasks'=>$tasks))
and my elements/pendingTasksLi.php file has the following
#foreach ($tasks as $task)
<li>
<a class="todo-actions" href="javascript:void(0)">
<i class="fa fa-square-o"></i>
<span class="desc" style="opacity: 1; text-decoration: none;">{{{$task\['title'\]}}}</span>
<span class="label label-danger" style="opacity: 1;"> {{{$task\['deadLineTime'\]}}}</span>
</a>
</li>
#endforeach
This code in the pendingTakstsLi file is never executed as a loop but only as a simple text.
This is what the output looks like...
#foreach ($tasks as $task)
{{{$task['title']}}} {{{$task['deadLineTime']}}}
#endforeach
I am not sure what to do... Please advise...
Check a screen here
http://i.stack.imgur.com/8emZk.png
Thanks
Jyot
You mentioned that your "pendingTasksLi" view ends in ".php" and not ".blade.php" which would prevent it from being parsed as a blade view.
I had the same problem and as mentioned above you forgot the .blade before the .php
If you want to use expressions like this: {{ $variable}} and want them to be parsed you always have to add .blade in the name pefore the .php extension of the file.

Resources