Reputation: 533
I'm trying to implement IF
condition with true/false or 1/0 in Vue Component. I go through some earlier asked questions but not able to get it. Please help me out.
IF
condition not gives true
output even if dd
gives true
.
Controller (I tried with two ways so that either I may got success with true/false or 1/0, In both methods on page I'm able to get 1/0 or true/false with dd($isExamAssigned)):
dd($isExamAssigned); // here I'm able to get 1 or 0
blade.php:
<quiz-component
:isExamAssigned = "{{$isExamAssigned}}"
>
</quiz-component>
code part from Component.vue:
props:['isExamAssigned'],
data(){
return{
isExamAssigned :this.isExamAssigned,
}
and here is the IF condition:
<div v-if="isExamAssigned === '1'">
<!-- Code here for IF -->
</div>
<div v-else>
<!-- Code here for ELSE -->
</div>
I tried different ways to get the values, like:
<div v-if="isExamAssigned === 1">
<div v-if="isExamAssigned === true">
<div v-if="isExamAssigned">
but Im not able to implement condition.
Thanks.
Upvotes: 9
Views: 11833
Reputation: 325
To transfer "Boolean Variable" from Blade to Vue in new versions of Laravel, the best way is to use :
before props name and use @js
for PHP variable.
for example:
<vue-component :props-name=@js($phpVariable) ></vue-components>
Upvotes: 0
Reputation: 38
Mrhn's answers is true.
You can make Laravel do the casting for you by setting the cast on the model.
// On a model, e.g. App\Models\Exam.php
$casts = ['is_exam_assigned' => 'boolean'];
https://laravel.com/docs/master/eloquent-mutators#attribute-casting
Upvotes: 1
Reputation: 171
Himanshu's answer is correct, it can also be written like:
:isExamAssigned='@json($isExamAssigned)'
Upvotes: 11
Reputation: 456
Try passing the prop like this in your blade.php file
:isExamAssigned="{{ json_encode($isExamAssigned) }}"
This will send the prop in Boolean format.
Upvotes: 19
Reputation: 18936
You are setting it to string value of '1'
in the vue component. Later you are strict comparing it to an integer, boolean and boolean again. The most correct approach would be to set it to a real boolean like so. The second approach you had would work.
$isExamAssigned = DB::table('quiz_user')->where('user_id', $authUser)->where('quiz_id', $quizId)->exists();
Now PHP type juggles weird, if you print out $isExamAssigned
it will print out 1. You can try with {{true}}
and see the result yourself. To avoid this, do the following check in your blade file when setting the component.
:isExamAssigned = "{{$isExamAssigned ? 'true' : 'false'}}"
This will make the following if statements work.
<div v-if="isExamAssigned === true">
<div v-if="isExamAssigned">
Upvotes: 5