Blade if(isset) is not working Laravel - php

Hi I am trying to check the variable is already set or not using blade version. But the raw php is working but the blade version is not. Any help?
controller:
public function viewRegistrationForm()
{
$usersType = UsersType::all();
return View::make('search')->with('usersType',$usersType);
}
view:
{{ $usersType or '' }}
it shows the error :
Undefined variable: usersType (View: C:\xampp\htdocs\clubhub\app\views\search.blade.php)

{{ $usersType or '' }} is working fine. The problem here is your foreach loop:
#foreach( $usersType as $type )
<input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span>
#endforeach
I suggest you put this in an #if():
#if(isset($usersType))
#foreach( $usersType as $type )
<input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span>
#endforeach
#endif
You can also use #forelse. Simple and easy.
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse

#isset($usersType)
// $usersType is defined and is not null...
#endisset
For a detailed explanation refer documentation:
In addition to the conditional directives already discussed, the #isset and #empty directives may be used as convenient shortcuts for their respective PHP functions

Use ?? , 'or' not supported in updated version.
{{ $usersType or '' }} ❎
{{ $usersType ?? '' }} ✅

Use 3 curly braces if you want to echo
{{{ $usersType or '' }}}

On Controller
$data = ModelName::select('name')->get()->toArray();
return view('viewtemplatename')->with('yourVariableName', $data);
On Blade file
#if(isset($yourVariableName))
//do you work here
#endif

You can use the ternary operator easily:
{{ $usersType ? $usersType : '' }}

#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse

Use ?? instead or {{ $usersType ?? '' }}

I solved this using the optional() helper. Using the example here it would be:
{{ optional($usersType) }}
A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type) in a view that is using old() helper.
value="{{ old('type', optional($users)->type }}"
Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.
https://laravel.com/docs/5.8/helpers#method-optional

Related

how to check is there a value in the other column of table?

In a laravel blade in third line of this code I want to check if parent_id exists in id column or not
please help me!
I'm using laravel 9
#if ($category->parent_id == 0)
no parent
#if ($category->parent_id)
no parent
#else
{{ $category->parent->name }}
#endif
I corrected it this way:
#elseif (empty($category->parent))
Using exists() function for parent()
Not that exists function works just with single relations (belongsTo, hasOne)
// This will run SQL query // returns boolean
$category->parent()->exists(); // Don't forget parentheses for parent()
If you want to save performance and not calling sql query
count($category->parent); // returns 0 if not exist
Balde:
you can use the empty() to check if empty.
#if ($category->parent == 0)
no parent
#elseif (empty($category->parent))
<p>no parent</p>
#else
{{ $category->parent->name }}
#endif
or ?? operator
{{ $category->parent_id ?? 'no parent' }}
You can use the is empty in twig as below:
{% if category is empty %}
<p> No parent </p>
{% endif %}
You can try by using isset() function
#if ($category->parent_id == 0)
no parent
#if (!isset($category->parent_id))
no parent
#else
{{ $category->parent->name }}
#endif

Call to undefined method error when I try to use links()

When I try to use $student->links() I see this error :
Facade\Ignition\Exceptions\ViewException
Call to undefined method App\Student::links()
I checked the controller, model etc but all of them seem OK... How can I fix this?
(I tried this code both on my Macbook and VPS -CentOS7- but same problem occurs)
That part of my view looks like this:
</tr>
#endforeach
</tbody>
</table>
{{ $student->links() }}
</div>
#endsection
Change
{{ $student->links() }}
to
{{ $students->links() }}
(use plural form).
You need to paginate in your backend code. $students = App\Student::paginate(15);
And then you can access the links()
<div class="container">
#foreach ($students as $student)
{{ $student->name }}
#endforeach
</div>
{{ $students->links() }}

Blade: Undefined Variable Inside Foreach Loop

I have a controller which gets an array of a User's diaries from my database and passes them to my view:
<?php
public function readDiaries($hash)
{
$user = User::where('hash', $hash)->first();
$diaries = Diary::where('user_id', $user->id)->get();
return view('app.diary.readDiaries', ['diaries' => $diaries]);
}
In my view, I am looping through the diaries using a #foreach loop.
<div id="diaries" class="card-columns">
#if (count($diaries) > 0)
#foreach ($diaries as $dairy)
{{ var_dump($diary) }}
#endforeach
#endif
</div>
But I am getting the following undefined variable error...
Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)
Why is my $diary variable undefined inside the #foreach loop?
You have a typo
change #foreach ($diaries as $dairy) to #foreach ($diaries as $diary)
and it should work!
There is some typo in var_dump use {{ var_dump($dairy) }}
Try to use compact method for pass data to view as shown below
//return view('app.diary.readDiaries', compact('diaries'));
public function readDiaries($hash)
{
$user = User::where('hash', $hash)
->first();
$diaries = Diary::where('user_id', $user->id)
->get();
return view('app.diary.readDiaries', compact('diaries'));
}
It is just a simple spelling mistake,
#foreach ($diaries as $dairy)
{{ var_dump($diary) }}
#endforeach
in your foreach you are passing $dairy and dumping var name is $diary
chane it to
#foreach ($diaries as $dairy)
{{ var_dump($dairy) }}
#endforeach
Habbit of copy paste is sometimes good for us...
:)
#foreach ($diaries as $dairy)
{{ var_dump($diary) }}
#endforeach
you used ($diaries as $dairy) in foreach
but in foreach you used ($diary)
you want edit this {{ var_dump($diary) }} to {{ var_dump($dairy) }}
or you want edit #foreach ($diaries as $dairy) to #foreach ($diaries as $diary)

Laravel array result set - Use of undefined constant name

I'm using Laravel 5.2 and returning an array result set to my view by using the following
return view('home')->with('devices', $devices)
I've attempted to loop through my array data by using the following in blade
#foreach($devices as $device)
{{ $device[name] }} has
{{ $device[views] }}
#endforeach
Using $device[name] throws Use of undefined constant name - assumed 'name'
I've also tried looping through the result like this
#foreach($devices as $device)
{{ $device->name }} has
{{ $device->views }}
#endforeach
You are sending it like constant not as string. Replace it like this:
#foreach($devices as $device)
{{ $device['name'] }}
{{ $device['views'] }}
#endforeach

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

Categories