Laravel check if var is does not exist - php

I have condition:
{{ setting('notifications.email.enabled') ? 'checked' : '' }}
In setting('notifications.email.enabled') can be values: 1, 0 and values can does not exist. How I can check if setting('notifications.email.enabled') does not exist (in table), and if does not exist, then 'checked'. Now I get '' on does not exist.

try this:
{{ setting('notifications.email.enabled', true) ? 'checked' : '' }}
by setting a default value in the second parameter

Compare it with 0 and return checked in else case such that if it is not set or it is 1 then it will return checked.
{{ (setting('notifications.email.enabled') === 0) ? '' : 'checked' }}

Related

Pre-selecting value on edit page with blade in laravel?

I have an issue where i want to show the current brand in a select, on the edit page of a vehicle mode.
The select has to contain all the brands, so it is possible to choose another brand on editing the model.
I have this in my vehicleModelsController edit:
$vehicle_brands = VehicleBrand::all();
$selected_vehicle_brand = VehicleBrand::first()->vehicle_brand_id;
return view('vehicleModels.edit', compact(['vehicleModel', 'vehicle_brands'], ['selected_vehicle_brand']));
And in my edit.blade file i have the following select:
<select class="form-control" name="vehicle_brand_id">
#if ($vehicle_brands->count())
#foreach($vehicle_brands as $vehicle_brand)
<option value="{{ $vehicle_brand->id }}" {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }}>
{{ $vehicle_brand->brand }}</option>
#endforeach
#endif
</select>
And it works just fine with editing, but it does not show the current value as selected, it shows the first value in the brand table.
I have Brand1, Brand2, Brand3 and Brand4 as test values in the brand table, but no matter what brand the model is related to, it shows Brand1 in the select on the edit page.
Any help is greatly appreciated!
In the controller you are assigning value of VehicleBrand::first()->vehicle_brand_id to $selected_vehicle_brand and then you are comparing it with id field in {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }}
If there is not column/field named vehicle_brand_id on VehicleBrand model then VehicleBrand::first()->vehicle_brand_id will be null. So when you compare $selected_vehicle_brand == $vehicle_brand_id it will be like null == $vehicle_brand->id which will be false for any id value.
So it should either be (in Controller)
$selected_vehicle_brand = VehicleBrand::first()->id;
//Here we are hard coding the value to be the id of first record of VehicleBrand
//However in practice it should come from either request/route param eg: $id received via the request/route param
//Or from VehicleModel being edited eg: $vehicleModel->vehicle_brand->id
And {{ $selected_vehicle_brand == $vehicle_brand->id ? 'selected="selected"' : '' }} in the view
Or, if vehicle_brand_id column/field exists on VehicleBrand, it should be (in Controller)
$selected_vehicle_brand = VehicleBrand::first()->vehicle_brand_id;
and {{ $selected_vehicle_brand == $vehicle_brand->vehicle_brand_id ? 'selected="selected"' : '' }}
The field you are comparing the values for should be the same.
And as a side note, if you are on Laravel 9 you can use #selected blade directive
#selected(old($vehicle_brand->id) == $selected_vehicle_brand)

Laravel 4.2 blade: check if empty

In Laravel blade you can do:
{{ $variable or 'default' }}
This will check if a variable is set or not. I get some data from the database, and those variables are always set, so I can not use this method.
I am searching for a shorthand 'blade' function for doing this:
{{ ($variable != '' ? $variable : '') }}
It is hard to use this piece or code for doing this beacuse of, I do not know how to do it with a link or something like this:
{{ $school->website }}
I tried:
{{ ($school->website != '' ? '{{ $school->website }}' : '') }}
But, it does not work. And, I would like to keep my code as short as possible ;)
Can someone explain it to me?
UPDATE
I do not use a foreach because of, I get a single object (one school) from the database. I passed it from my controller to my view with:
$school = School::find($id);
return View::make('school.show')->with('school', $school);
So, I do not want to make an #if($value != ''){} around each $variable (like $school->name).
try this:
#if ($value !== '')
{{ HTML::link($value,'some text') }}
#endif
I prefer the #unless directive for readability in this circumstance.
#unless ( empty($school->website) )
{{ $school->website }}
#endunless
With php 7, you can use null coalescing operator. This is a shorthand for #m0z4rt's answer.
{{ $variable ?? 'default' }}
{{ ($school->website != '' ? '{{ $school->website }}' : '') }}
change to
{{ ($school->website != '') ? '' . $school->website . '' : '' }}
or the same code
{{ ($school->website != '') ? "<a href='$school->website' target='_blank'>$school->website</a>" : '' }}
{{ isset($variable) ? $variable : 'default' }}
I wonder why nobody talked about $variable->isEmpty() it looks more better than other. Can be used like:
#if($var->isEmpty())
Do this
#else
Do that
#endif
From Laravel 5.4, you can also use the #isset directive.
#isset($variable)
{{-- your code --}}
#endisset
https://laravel.com/docs/9.x/blade#if-statements

Laravel blade check box

I want to set check-boxes state from database, so I write,
{{ Form::checkbox('asap', null, $offer->asap) }}
But if I want to set 'id' to the check-box like
{{ Form::checkbox('asap', null, $offer->ASAP, array('id'=>'asap')) }}
It always set my check-box state to true. (Before user select it)
So question how set 'id' in blade check-boxes when check-box state is set before user select it?
I know this question was answered before, in this one I am going to explain step by step how to implement checkboxes with Laravel/blade with different cases ...
So in order to load your checkboxes from the database or to test if a checkbox is checked :
First of all you need to understand how it works, as #itachi mentioned :
{{ Form::checkbox( 1st argument, 2nd argument, 3rd argument, 4th
argument ) }}
First argument : name
Second argument : value
Third argument : checked or not checked this takes: true or
false
Fourth argument : additional attributes (e.g., checkbox css classe)
Example :
{{ Form::checkbox('admin') }}
//will produces the following HTML
<input name="admin" type="checkbox" value="1">
{{ Form::checkbox('admin', 'yes', true) }}
//will produces the following HTML
<input checked="checked" name="admin" type="checkbox" value="yes">
How to get checkboxes values ? ( in your controller )
Methode 1 :
public function store(UserCreateRequest $request)
{
$my_checkbox_value = $request['admin'];
if($my_checkbox_value === 'yes')
//checked
else
//unchecked
...
}
Methode 2 :
if (Input::get('admin') === 'yes') {
// checked
} else {
// unchecked
}
Note : you need to assign a default value for unchecked box :
if(!$request->has('admin'))
{
$request->merge(['admin' => 0]);
}
this is nice right ? but how could we set checked boxes in our view ?
For good practice I suggest using Form::model when you create your
form this will automatic fill input values that have the same names as
the model (as well as using different blade Form:: inputs ..)
{!! Form::model( $user, ['route' => ['user.update', $user->id], 'method' => 'put' ]) !!}
{!! Form::checkbox('admin', 1, null) !!}
{!! Form::close() !!}
You can also get it like this :
{{ Form::checkbox('admin',null, $user->admin) }}
Okey now how to deal with :
multiples checkboxes
Add css classe
Add checkbox id
Add label
let's say we want to get working days from our database
$working_days = array( 0 => 'Mon', 1 => 'Tue', 2 => 'Wed',
3 => 'Thu', 4 => 'Fri', 5 => 'Sat', 6 => 'Sun' );
#foreach ( $working_days as $i => $working_day )
{!! Form::checkbox( 'working_days[]',
$working_day,
!in_array($working_days[$i],$saved_working_days),
['class' => 'md-check', 'id' => $working_day]
) !!}
{!! Form::label($working_day, $working_day) !!}
#endforeach
//$saved_working_days is an array of days (have 7 days, checked & unchecked)
I've spent sometime to figure out how to deal with multiple checkboxes I hope this can help someone :)
3rd argument decides whether checkbox is checked or not. So probably $offer->ASAP (or $offer->asap is true (or not false or not null). If you want to to make checkbox unchecked either set it to false, or don't use 3rd argument (set to to null or false):
{{ Form::checkbox('asap',null,null, array('id'=>'asap')) }}
EDIT
Another possibility is that you have on your page some custom JavaScript code that finds element by asap id and checks this checkbox. So when you don't set id, JavaScript cannot check it, but when you set this id, the checkbox will be checked by JavaScript.
in FormBuilder.php
public function checkbox($name, $value = 1, $checked = null, $options = array())
{
return $this->checkable('checkbox', $name, $value, $checked, $options);
}
1st param: name
2nd : value
3rd : checked or not (i.e. null, false or true)
4th : attributes.
{{ Form::checkbox('asap',null,$offer->ASAP, array('id'=>'asap')) }}
your order is wrong.
it should be,
{{ Form::checkbox('asap',$offer->ASAP, null, array('id'=>'asap')) }}
Good luck!
<div class="togglebutton">
<label>
#if ($programmer->play === 1)
<input type="checkbox" name="play" checked="">
#else
<input type="checkbox" name="play" {{ old('play') ? 'checked' : '' }} >
#endif
Play
</label>
</div>

Is there a Twig shorthand syntax for outputting conditional text

Is there a shorter syntax in Twig to output a conditional string of text?
<h1>{% if not info.id %}create{% else %}edit{% endif %}</h1>
Traditional php is even easier than this:
<h1><?php info['id']? 'create' : 'edit' ?></h1>
This should work:
{{ not info.id ? 'create' : 'edit' }}
Also, this is called the ternary operator. It's kind of hidden in the documenation: twig docs: operators
From their documentation the basic structure is:
{{ foo ? 'yes' : 'no' }}
If you need to compare the value is equal to something you can do :
{{ user.role == 'admin' ? 'is-admin' : 'not-admin' }}
You can use the Elvis Operator inside twig :
{{ user ? 'is-user' }}
{{ user ?: 'not-user' }} // note that it evaluates to the left operand if true ( returns the user ) and right if not
The null-coalescing operator also working, like:
{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}

Twig ternary operator, Shorthand if-then-else

Does Twig support ternary (shorthand if-else) operator?
I need some conditional logic like:
{%if ability.id in company_abilities %}
<tr class="selected">
{%else%}
<tr>
{%endif%}
but using shorthand in Twig.
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
Support for the extended ternary operator was added in Twig 1.12.0.
If foo echo yes else echo no:
{{ foo ? 'yes' : 'no' }}
If foo echo it, else echo no:
{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
If foo echo yes else echo nothing:
{{ foo ? 'yes' }}
or
{{ foo ? 'yes' : '' }}
Returns the value of foo if it is defined and not null, no otherwise:
{{ foo ?? 'no' }}
Returns the value of foo if it is defined (empty values also count), no otherwise:
{{ foo|default('no') }}
If the price exists from the database for example then print (Price is $$$) else print (Not Available) and ~ for the concatenation in Twig.
{{ Price is defined ? 'Price is '~Price : 'Not Available' }}
I just used a as a general variable name. You can also use endless if else like this:
{{ a == 1 ? 'first' : a == 2 ? 'second' : 'third' }}

Categories