Outputting a null var in a if statement? - php

I am returned either a 1 or null from a method in a third party package. I need to check this in a vue template statement like so:
v-if="{{ $myVar }} || {{ $thirdPartVar }}"
Either var needs to be true.
The issue is when the $thirdPartyVar is null, the statement errors as there is nothing after the ||.
How can I output a null var to be true or false in this situation?
The error is: - invalid expression: Unexpected token }

You should remove the extra brackets because it's not a valid vue template syntax
v-if="$myVar || $thirdPartVar"

Related

Cannot get variable from custom Blade directive - Curly braces lost?

I am using Laravel 7. I am thinking of using Blade directive to format numbers in my view. But I'm having problem with the variable showing up in the final output.
Here is a simplified version of my original code that works. (The actual code has a number of conditional #if to format the number differently depending on the value.)
<div>{{ number_format( $stat->number1,0,'.',',' ) }}</div>
<div>{{ number_format( $stat->number2,0,'.',',' ) }}</div>
<div>{{ number_format( $stat->number3,0,'.',',' ) }}</div>
Here is the custom directive I created.
Blade::directive('format_number_thousand_sep', function ($expression) {
return "{{ number_format( $expression,0,'.',',' ) }}";
});
Here is the blade template that I've changed to call this directive. When I run this, it gives me an error "number_format() expects parameter 1 to be float, string given". I figured the string "$stat->number1" is being used instead of the value of the variable.
<div>#format_number_thousand_sep( '$stat->number1' )</div>
<div>#format_number_thousand_sep( '$stat->number2' )</div>
<div>#format_number_thousand_sep( '$stat->number3' )</div>
To troubleshoot, I modified the directive to just return the variable to make sure it displays on the output. I've tried variations like the ones below and the output is an error (e.g. unexpected '{'), the literal string "$stat->number1", or a partial string because the "
return "$expression";
return "{{ $expression }}";
return "<?php echo '{{' . $expression . '}}'; ?>";
I've tried researching this online. Most questions seems to be trying to use the value of the variable within the directive, which I know wouldn't work. I just want the output to include the proper syntax so the variable value will be inserted in the output.
What is the proper syntax for passing a variable name to a blade directive and have it evaluate properly in the final output?
I'm not sure but can you try like this:
Blade::directive('format_number_thousand_sep', function ($expression) {
return number_format( $expression,0,'.',',' );
});

Laravel: redirect with custom error but without error message

Consider the manual authentication. If the order ID has not been found in database, we redirect user to page with input fields and with error 'wrongOrderId':
public function login(Request $request) {
$inputted_orderId = $request->input('order_id');
$orderIdInDB = DB::table(self::SITE_IN_DEVELOPMENT_TABLE_NAME)
->where(self::ORDER_ID_FIELD_NAME, $inputted_orderId)->first();
if (is_null($orderIdInDB)) {
return Redirect::route('loginToSitesInDevelopmentZonePage')->withErrors('wrongOrderId');
}
}
In this example, we don't need to pass the error message: the message box is already exists in View; all we need is to display this message box when user has been redirected with error 'wrongOrderId':
#if (!empty($errors->first('wrongOrderId')))
<div class="signInForm-errorMessagebox" id="invalidID-errorMessage">
<!-- ... -->
</div>
#endif
All above code is working without laravel/php errors; I get into is_null($orderIdInDB) if-block when input wrong order number, however the error message box don't appears. I tried a lot of ways, and (!empty($errors->first('wrongOrderId'))) is just last one. What I doing wrong?
Did you try printing {{$errors->first()}}?
first(string), works as a key value pair, it invokes its first key VALUE
try this,
#if($errors->any())
<div class="signInForm-errorMessagebox" id="invalidID-errorMessage">
<!-- ... -->
</div>
#endif
If you want to get specific error from validator error, use the get() method.
$errors->get('wrongOrderId'); get all the wrongOrderId errors.
$errors->first('wrongOrderId'); get first error of wrongOrderId errors
I explored that $errors->first('wrongOrderId') has non-displayable but non-null value. So #if ( $errors->first('wrongOrderId') !== null ) will work.
Something more elegantly like #if ($errors->first('wrongOrderId'))? Unfortunately just one this check is not enough: even if we define
return Redirect::route('loginToSitesInDevelopmentZonePage')->withErrors(['wrongOrderId' => true]);
php will convert true to 1. So, #if ( $errors->first('wrongOrderId') == true ) will working, but #if ($errors->first('wrongOrderId')) will not.
However, we can to cast $errors->first('wrongOrderId') to bool, so the most elegant solution will be
#if ((bool) $errors->first('wrongOrderId'))

Check if null and empty string in Laravel view

in my view I have to output separately the one that is null and the one that is empty string
so i have this:
#if( $str->a == null)
... // do somethin
#endif
#if( $str->a == '')
... // do somethin
#endif
the problem is they the same result.
Thanks
In the comments you've said you only want to check if it is null. So, use is_null():
#if (is_null($str->a))
// do somethin
#endif
#if( !empty($str->a))
... // do somethin
#endif
This are consider for empty
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
You can try this
#isset($str->a)
// $str->a is defined and is not null...
#endisset
#empty($str->a)
// $str->a is "empty"...
#endempty
If Statements Laravel docs
$str->a can't be null and '' at the same time. Have you tried #elseif?
#if( is_null($str->a))
... // do somethin
#elseif( $str->a == '')
... // do somethin
#endif
actually, it should only shows the ones that is null and not the one that is empty.
It sounds like you want to check if $str->a is a valid string or not. As suggested in comments by #GrumpyCrouton you can use empty().
#if( empty($str->a))
... // do somethin
#endif

How to handle Undefined Offset in laravel?

I am getting this error when I land on the page after logging in:
ErrorException in compiled.php line 11573: Undefined offset: 0 (View:
C:\xampp\htdocs\campusguru\resources\views\home.blade.php)
I know that the cause of this error is the empty variable that I passed to the view.
I have already tried:
if(isset($blog)) { do something }
and in blade view as:
{{ $blogs[0]->title or '' }}
Is there anyway I could handle this error. Or is there a better way of doing it?
Try the following:
{{ isset($blogs[0]) ? $blogs[0]->title : '' }}
If you are using a foreach to get every $blog->title use
#foreach ($blogs as $blog)
{{ $blog->title }}
#endforeach
The problem is that $blogs is actually defined and its value is [] (i.e. empty array) so it means that isset($blogs) statement will evaluate to true. Same thing is valid for collections. If a collection is empty (i.e. has no elements but it's defined) isset($blogs) will still evaluate to true but accessing $blogs[0] will cause an Undefined offset: 0 error.
You could try the following solutions:
Using count
if(count($blogs)) { /* do something */ }
if $blogs = [] or $blogs = null the function count will return zero so that means that $blogs is empty.
Using empty
if(!empty($blogs)) { /* do something */ }
This is the equivalent of writing !isset($var) || $var == false as described in the PHP Manual - empty:
Returns FALSE if var exists and has a non-empty, non-zero
value. Otherwise returns TRUE.
The following things are considered to be empty: "" (an
empty string) 0 (0 as an integer) 0.0 (0 as a
float) "0" (0 as a string) NULL
FALSE array() (an empty array) $var; (a
variable declared, but without a value)
Checking if a collection is empty
If $blogs is a Collection is sufficient to check if it is not empty using `isNotEmpty() method:
#if($blogs->isNotEmpty()) <!-- Do your stuff --> #endif
EDIT
I forgot to add the blade syntax:
#if(count($blogs)) <!-- Do whatever you like --> #endif
or
#if(!empty($blogs)) <!-- Do whatever you like --> #endif
EDIT 2
I'm adding more content to this answer in order to address some of the issues presented in the comments. I think that your problem is the following:
$blogs is an empty collection, so it's defined but it has no elements. For this reason the if(isset($blogs)) statement will evaluate to true passing the first if condition. In your blade template you are making the check {{ $blogs[0]->title or '' }} that is absolutely not equal to <?php isset($blogs[0]->title) ? $blogs[0]->title : '' ?> as pointed out in the comments, but it is an expression that will return true or false, so it will never print out title parameter even if $blogs[0] exists. The problem here is that when checking the condition $blogs[0]->title you are actually accessing the element 0 of the $blogs collection that will trigger the exception Undefined offset: 0 because the collection is actually empty. What i was saying is that in addition to the
if(count($blogs)) { /* do something */ }
(that checks that $blogs is set and that it's length is greater than 0) in your template you should do
{{ isset($blogs[0]->title) ? $blogs[0]->title : '' }}
or more concisely
{{ $blogs[0]->title ?: '' }}
assuming that the control flow will arrive there only if the $blogs passed the first if. If the issue still persists the problem is elsewhere in your code IMHO.
You can simply solve this with the data_get() helper.
For example:
php artisan tink
Psy Shell v0.8.11 (PHP 7.0.22-0ubuntu0.16.04.1 — cli) by Justin Hileman
>>>
>>> $a = collect([[], null, App\Models\User::find(1)]);
=> Illuminate\Support\Collection {#887
all: [
[],
null,
App\Models\User {#896
id: 1,
name: "user1",
email: "user1#thisisdevelopment.nl",
last_name: "Gabrielle",
first_name: "Rempel",
deleted_at: null,
created_at: "2017-08-12 15:32:01",
updated_at: "2017-09-05 12:23:54",
},
],
}
>>> data_get($a[0], 'name', 'nope');
=> "nope"
>>> data_get($a[1], 'name', 'nope');
=> "nope"
>>> data_get($a[2], 'name', 'nope');
=> "user1"
>>>
So in this case:
{{ data_get($blogs[0], 'title', '') }}
data_get() will work both on arrays and objects, returning the key or attribute defined in the second param (this can be laravel.dot.notation.style, or just an array), the 3rd param will be the default return value if the object/array or the key/attribute does not exist, the default is null.
Edit:
Just saw the request for the extra explanation on why the original code wasn't working.
Index 0 simply does not exist on the array/collection that is passed to the view.
>>> $a = [1 => App\Models\User::find(1)];
=> [
1 => App\Models\User {#890
id: 1,
name: "user1",
// ... etc
},
]
>>> $a[0]->name ?: 'nope';
PHP error: Undefined offset: 0 on line 1
>>> $a[1]->name ?: 'nope';
=> "user1"
It doesn't matter if OP used the blade or default, it doesn't even make it to the ternary statement because of the missing 0 index on $blogs.
Edit 2 as requested:
So the reason you get the Undefined offset: x error is because of the order in which PHP evaluates the code.
Blade's or default is behind the scenes nothing more than a ternary statement:
return preg_replace('/^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/si', 'isset($1) ? $1 : $2', $value);
So this will make:
isset($blogs[0]->title) ? $blogs[0]->title : ''
isset() will check if title on the object is set, but to do so, it will require $blogs[0] to be a valid object. In order to do that, it will try and get the object from the $blogs array at index 0. But since this index does not exist, it will trigger the Exception with an Undefined offset: 0.
In order to make this work with Blade's or default, you would first have to ensure that $blogs[0] is defined (and preferably also check that it's an object, otherwise you'll get the trying to get property of non-object error, please note that this should not be the responsibility of the view), after that you would be able to use the or default as you would any other time.
#if (isset($blogs[0]) && is_object($blogs[0]))
{{ $blogs[0]->title or '' }}
#else
// some other default placeholder
#endif
Basically you will get the same offset error when using data_get(), because index 0 still does not exist.
{{ data_get($blogs[0], 'title', '') }} // Undefined offset: 0
You could play dirty and do this (this would not pass any code review anywhere and I should not have typed this at all, this is just to illustrate)
{{ data_get($blogs, '0.title', '') }} // Will display '' as it will check if key 0 exists
Anyway, with data_get() you would still end up doing something like this, as you would need to make sure $blogs[0] is something you can work with:
#if (isset($blogs[0]))
{{ data_get($blogs[0], 'title', '') }}
#else
// some other default placeholder
#endif
Bottomline, the best option would be not to rely on indexes like this in your view, this is simply not the responsibility of your view.
Blade's or default works perfectly on single variables, but when dealing with object attributes, you would just have to make sure the (parent) object exists when doing so.
I do this way in controller:
if (empty($allFares) || count($allFares)==0){
return back()->withError('No Fare Found For The City!');
}
OR in blade:
#if (!empty($allFares) || count($allFares)>0)
#foreach(allFares as $key=>$value)
#endforeach
#endif
If you have an object that's passed to the view and let's say your data is "posts" which is being held inside an object like this:
$obj->posts.
If you then go and do a foreach loop which would iterate trough every post and print out its parameters like in the example below it works perfectly well when you actually have posts.
#foreach($obj->posts as $post)
<h1>$post->title</h1>
<p>$post->content</p>
#endforeach
Before doing the loop you'd want to check if attribute has been set with values. You can use isset() for this, and since it's a special form it can be used as isset($obj->posts) or isset($obj->posts[0]). The difference is that the latter will only check if the array key has any value so if your index key is anything but 0, it'll return false. For instance you have:
$foo = ['first' => somevalue1, 'second' => somevalue2];
isset($foo[0]); //returns false
isset($foo['first']); //returns true
isset($foo); //returns true
The way I'd make the check is the following:
#if(isset($obj->posts))
#foreach($obj->posts as $post)
...
#endoforeach
#endif
As of PHP7 you can use null coalescing operator ?? for checking ternary conditions:
#if($posts?? '')
#foreach($posts as $post)
<h1>$post->title</h1>
<p>$post->content</p>
#endforeach
#endif
And if you want to print any variable directly then check first that the variable exists or not in condition, so you can do as below:
{{ $blogs && $blogs[0]->title ? $blogs[0]->title : '' }}
For simply solving the issue use the # operator (error control operator)
{{ #$blogs[0]->title }}
The # error control operator (also called STFU operator with mixed feelings), that suppresses errors just for the expression that immediately follows.

Twig get url parameter with []

I have an url like : MYURL?filter[_per_page]=25&filter[name][value]=hello
How can i get these parameters with twig ?
I'm trying {{ app.request.get('filter[_per_page]') }} but it's always empty...
Thanks !
Edit : I'm in javascript an i want to assign this result to a javascript variable like : var param = "{{ app.request.get('filter[_per_page]') }}";
You must manage as an array accessing to the filter element as:
{{ app.request.get('filter')['_per_page'] }}
(This time I try before posting...)
You've almost got it.
app object is GlobalVariables instance. When you say app.request, getRequest() is being invoked and returns an instance of standard Request object.
Now if you look at Request::get() (link) there is:
get(string $key, mixed $default = null, bool $deep = false)
I think what you need to do is this:
{{ app.request.get('filter[_per_page]', NULL, true) }}
Where NULL is default value and true means deep traversal of Request object.
I found a solution like this :
app.request.attributes.get('request').query.get('param_name')
To access to array of query params you can use:
app.request.attributes.get('_route_params');
You can see different solutions on the documentation.

Categories