AlpineJS: How can I add a class to an element conditionally? - laravel

I have an array of messages being pulled into view thanks to Laravel Echo, Livewire, and AlpineJS.
<div class="mt-4 rounded-lg p-6"
x-data="{{ json_encode(['messages' => $messages, 'messageBody' => '']) }}"
x-init="
Echo.join('demo')
.listen('MessageSentEvent', (e) => {
#this.call('incomingMessage', e)
})
">
<template x-if="messages.length > 0">
<template
x-for="message in messages"
:key="message.id"
>
<div class="my-8">
<div class="flex flex-row justify-between border-b border-gray-200">
<span class="text-white-600 chat-block-author" x-text="message.user.name"></span>: <span class="text-white-800" x-text="message.body" style="margin-left:10px;"></span>
</div>
</div>
</template>
</template>
</div>
I want to dynamically add a class called chat-block-author when the rendered message belongs to the logged-in user. The Message model does contain user_id for each item, but I can't seem to get AlpineJS to play well with conditional logic like I could with Blade.
Any tips?
This does not work
<template x-if="message.user_id == {{ Auth::user()->id }}">
<div class="my-8">
<div class="flex flex-row justify-between border-b border-gray-200">
<span class="text-white-600 chat-block-author" x-text="message.user.name"></span>: <span class="text-white-800" x-text="message.body" style="margin-left:10px;"></span>
</div>
</div>
</template>
as it produces this error
Uncaught (in promise) ReferenceError: message is not defined
at eval (eval at tryCatch.el.el (alpine.js?df24:1), <anonymous>:3:36)
at tryCatch.el.el (alpine.js?df24:140)
at tryCatch (alpine.js?df24:127)
at saferEval (alpine.js?df24:135)
at Component.evaluateReturnExpression (alpine.js?df24:1747)
at eval (alpine.js?df24:1714)
at Array.forEach (<anonymous>)
at Component.resolveBoundAttributes (alpine.js?df24:1696)
at Component.updateElement (alpine.js?df24:1672)
at eval (alpine.js?df24:1628)

You did not mention where you want to add that class to, but in AlpineJS you can dynamically assign any attribute including classes by doing something like this:
<div :class="{ 'chat-block-author': message.user_id === {{ Auth::user()->id }} }" class="your-other-classes go-here">
...
</div>
Note that you can also use it with an existing class attribute, the attributes defined in :class are dynamically added to your class attribute if the specified condition is true.

Related

Laravel Pagination not working in Blade file with Tailwind CSS

I'm trying to use Laravel pagination. The issue is that when I use the links() method in the Blade file, it gives an error. For example, when I use the URL "http://127.0.0.1:8000/tournaments?page=3," it works fine, but it gives an error in the Blade file, as explained below.
Controller
public function index()
{
return view('front.tournaments', [
'seriesdata' => $this->tournamentList()
]);
}
public function tournamentList()
{
return Series::leftJoin('team_squads as ts', 'ts.id_series', 'series.id')
->leftJoin('series_team_squads as sts', 'sts.id_series', 'series.id')
->leftJoin('admins as a', 'a.adminable_id', 'series.id')
->where('series.lang', 'en')
->orderBy('series.id', 'asc')
->groupBy('series.id')
->select('series.*')
->paginate(10)
->append([
'logo_url',
'location'
]);
}
Blade
#foreach($seriesdata as $series)
<div class="flex flex-inline xs:flex-col sm:flex-row">
<div class="w-full border-b">
<div class="flex justify-center items-start">
<div class="py-2 mx-auto sm:bg-white xs:bg-white w-full">
<a href="{{ url('tournaments/').'/'.$series->url.'/'.$series->id }}" class="flex">
<div class="grid grid-rows-1 grid-flow-col gap-1">
<div class="row-span-1 col-span-2">
<img src="{{ $series->logo_url }}" alt="avatar" class="object-cover w-12 h-12 mx-4">
</div>
<div class="row-span-1 col-span-2">
<h1 class="font-bold text-lg">{{ $series->name }}</h1>
<p class="uppercase font-light text-sm text-grey">{{ $series->location->address }}</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
#endforeach
{{ $seriesdata->links() }}
Error
It looks like your append() method is blocking pagination in blade. Try to remove it from tournamentList() in controller.
When you do ->append() after the ->paginate(), you are transforming what ->paginate() returns (basically a LenghtAwarePaginator) into a Collection, and Collection does not have a ->links() method. You can see this as the error shows you are trying to call links method in Illuminate\Database\Eloquent\Collection, that is how I know what ->append() is returning.

Custom validation on radio buttons if not selected | Tailwind

How to validate by showing a red ring around the radio button and make text red. Currently I am just showing a validation popup message. See image for a better idea.
Radio component
<input type="radio" {!! $attributes->class(['border-gray-300 text-gray-600 shadow-sm focus:border-gray-300 focus:ring focus:ring-gray-200 focus:ring-opacity-50', 'border-red-500 text-red-500' => $errors->has($attributes->get('name'))]) !!} />
Livewire view snippet
<div class="space-y-5">
#foreach ($ticket_types as $ticket_type)
<div>
<div class="relative flex items-start">
<div class="absolute flex items-center h-5">
<x-radio-button wire:model="ticket_type" #click="isQuestion = false" id="{{ $ticket_type->id }}" aria-describedby="{{ $ticket_type->id }}_description" value="{{ $ticket_type->id }}" class="h-4 w-4 transition duration-150 ease-in-out" />
</div>
<div class="pl-7 text-sm leading-5">
<x-jet-label for="{{ $ticket_type->id }}_title">
{{ $ticket_type->title }}
</x-jet-label>
<p id="{{ $ticket_type->id }}_description" class="text-gray-500">
{{ $ticket_type->description }}
</p>
</div>
</div>
</div>
#endforeach
</div>
<x-input-error for="ticket_type" />
Current look and feel
What I want to achieve (ignore the checkbox part)
You can conditionally include classes on components. So you could do something like:
<input type="radio"
{!! $attributes->class([
// these styles are applied by default
'border-gray-300 text-gray-600 shadow-sm focus:border-gray-300 focus:ring focus:ring-gray-200 focus:ring-opacity-50',
// these are applied if the name of the component is found in the error bag
// meaning there was an error
'border-red-500 text-red-500' => $errors->has($attributes->get('name'))
])
!!} />

Unable to swap Jetstream default TailwindCSS modal for Bootstrap Modal and still achieve the expected or same result as its was with TailwindCSS

Am working on a Laravel 8 package that swaps the #TALL stack for what I call the #BALL stack, and its basically a Bootstrap, AlpineJs Laravel, Livewire stack. Bootstrap 5 is leaning towards utility classes and no longer makes use of JQuery which gives room for AlpineJs so I really don't see a lot of upsides with Tailwind, not to mention I've gotten really comfortable with Bootstrap which should be all that matters at the end right?
Now the problem is this, I've been able to make changes to a lot of the JetStream blade files and if youve install Jetstream then your familiar with this image:
(Yes!!!! Its the exact same thing but with Bootstrap!)
but one particular component has kept me up for days and its the Bootstrap Modal.
Whenever I call the Bootstrap modal Livewire requests seem to make the Modal itself disappear leaving just the backdrop, forcing a page request before anything else can be clicked.
The final request is never completed
I have no way to hold the modal until a confirmation request is loaded and then programmatically disable the modal when finished.
The exact place I have this problem is in the views/api/api-token-manager.blade which is added by Jetstream when you install the livewire stack. My files looks like so:
My views/api/api-token-manager.blade
<!-- API Token List -->
// Inside a x-jet-action-section component
<x-slot name="content">
<div class="space-y-6">
#foreach ($this->user->tokens->sortBy('name') as $token)
<div class="d-flex justify-content-between">
<div>
{{ $token->name }}
</div>
<div class="d-flex">
#if ($token->last_used_at)
<div class="text-sm text-muted">
Last used {{ $token->last_used_at->diffForHumans() }}
</div>
#endif
#if (Laravel\Jetstream\Jetstream::hasPermissions())
<button class="btn btn-link text-secondary" data-toggle="modal"
wire:click="manageApiTokenPermissions({{ $token->id }})"
data-target="#managingApiTokenPermissions-{{ $token->id }}">
Permissions
</button>
#endif
<button class="btn btn-link text-danger text-decoration-none"
data-toggle="modal"
data-target="#confirmApiTokenDeletion-{{ $token->id }}">
Delete
</button>
</div>
</div>
<!-- API Token Permissions Modal -->
<x-jet-dialog-modal id="managingApiTokenPermissions-{{ $token->id }}">
<x-slot name="title">
API Token Permissions
</x-slot>
<x-slot name="content">
<div class="mt-2 row">
#foreach (Laravel\Jetstream\Jetstream::$permissions as $permission)
<div class="col-6">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="{{ $permission }}" wire:model.defer="updateApiTokenForm.permissions">
<label class="form-check-label">
{{ $permission }}
</label>
</div>
</div>
#endforeach
</div>
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button data-dismiss="modal">
{{ __('Nevermind') }}
</x-jet-secondary-button>
<x-jet-button class="ml-2" wire:click="updateApiToken"
wire:click="$emit('updateApiToken', {{ $token->id }})"
data-dismiss="modal">
{{ __('Save') }}
</x-jet-button>
</x-slot>
</x-jet-dialog-modal>
#push('scripts')
<script>
Livewire.on('updateApiToken', id => {
#this.manageApiTokenPermissions(id)
#this.updateApiToken()
})
</script>
#endpush
<!-- Delete Token Confirmation Modal -->
<x-jet-confirmation-modal id="confirmApiTokenDeletion-{{ $token->id }}">
<x-slot name="title">
Delete API Token
</x-slot>
<x-slot name="content">
Are you sure you would like to delete this API token?
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button data-dismiss="modal">
Nevermind
</x-jet-secondary-button>
<x-jet-danger-button class="ml-2"
wire:click="$emit('deleteApiToken', {{ $token->id }})"
data-dismiss="modal">
Delete
</x-jet-danger-button>
</x-slot>
</x-jet-confirmation-modal>
#push('scripts')
<script>
Livewire.on('deleteApiToken', id => {
#this.confirmApiTokenDeletion(id)
#this.deleteApiToken()
})
</script>
#endpush
#endforeach
</div>
</x-slot>
My x-jet-dialog-modal component
#props(['id' => null, 'maxWidth' => null])
<x-jet-modal :id="$id" :maxWidth="$maxWidth" {{ $attributes }}>
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ $title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
{{ $footer }}
</div>
</div>
</x-jet-modal>
My x-jet-modal component
#props(['id', 'maxWidth', 'modal' => false])
#php
$id = $id ?? md5($attributes->wire('model'));
switch ($maxWidth ?? '') {
case 'sm':
$maxWidth = ' modal-sm';
break;
case 'md':
$maxWidth = '';
break;
case 'lg':
$maxWidth = ' modal-lg';
break;
case 'xl':
$maxWidth = ' modal-xl';
break;
case '2xl':
default:
$maxWidth = '';
break;
}
#endphp
<!-- Modal -->
<div class="modal fade" tabindex="-1" id="{{ $id }}" aria-labelledby="{{ $id }}" aria-hidden="true">
<div class="modal-dialog{{ $maxWidth }}">
{{ $slot }}
</div>
</div>
I really don't want to make the change to Tailwind regardless of the hype so I would love any assistance the community can render.
To make a direct contribution to the project click here.
Thanks!!!
I was able to solve the above problem with Livewire Event. Its important to note that the reason for all this hassle was to create assets to replace Jetstream assets without affecting the business logic i.e. MODEL and CONTROLLER.
Here is what my solution looks like:
<div class="mt-3">
<x-jet-danger-button wire:click="$emit('confirmingUserDeletion')"
wire:loading.attr="disabled">
Delete Account
</x-jet-danger-button>
</div>
<!-- Delete User Confirmation Modal -->
<x-jet-dialog-modal id="confirmingUserDeletionModal">
<x-slot name="title">
Delete Account
</x-slot>
<x-slot name="content">
Are you sure you want to delete your account? Once your account is deleted, all of its resources and data will be permanently deleted. Please enter your password to confirm you would like to permanently delete your account.
<div class="mt-4 w-75" x-data="{}" x-on:confirming-delete-user.window="setTimeout(() => $refs.password.focus(), 250)">
<x-jet-input type="password" class="{{ $errors->has('password') ? 'is-invalid' : '' }}" placeholder="Password"
x-ref="password"
wire:model.defer="password"
wire:keydown.enter="deleteUser" />
<x-jet-input-error for="password" />
</div>
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button wire:click="$toggle('confirmingUserDeletion')"
wire:loading.attr="disabled"
data-dismiss="modal">
Nevermind
</x-jet-secondary-button>
<x-jet-danger-button wire:click="deleteUser" wire:loading.attr="disabled">
Delete Account
</x-jet-danger-button>
</x-slot>
</x-jet-dialog-modal>
#push('scripts')
<script>
Livewire.on('confirmingUserDeletion', () => {
#this.confirmUserDeletion()
new Bootstrap.Modal(document.getElementById('confirmingUserDeletionModal')).toggle()
})
</script>
#endpush

Delete nested object from array in Vue

trying to delete a nested object from an array. I've done some research and came across an example similar to mine, Vue.js Remove a Nested Object from Array.
However my issue is a slight more complex as I am trying to delete the object with ajax request. Essentially my engagement array contains nested objects of questions
so here is how I am displaying the list of questions for the engagement
<div v-for="question in engagement.questions" :key="question.id">
<div>
<div ">
{{ question.question }}
</div>
<div >
<span>Answered: </span>
<input type="checkbox" v-model="question.answered">
</div>
</div>
</div>
this is the button that will delete the question
<b-btn #click="deleteQuestion(engagement, question)">Confirm</b-btn>
and this is method that dispatches to the store
deleteQuestion(engagement, question) {
this.$store.dispatch('deleteQuestion', id)
.then(() => {
this.$router.push({path: '/engagement/' +this.engagement.id , query: {alert: 'The Question Was Succesfully Deleted'}});
})
},
and this is the store method
deleteQuestion(context, id) {
axios.delete('/questions/' + id)
.then(response => {
context.commit('deleteQuestion', id)
})
.catch(error => {
console.log(error)
})
},
Right now my alarm is getting “id is not defined” although I have other variations of this code where I will get a 500 internal server error which makes me think that I am not properly capturing the id of the question so it knows which one to delete…
below is the alarm I am getting in the console. I also did which is what the first arrow is pointing to for the observer
console.log(question)
the issue was that the b-model element that contained the #click="deleteQuestion" was outside of the div that contained the v-for so when I would click on the b-modal button it wasn't grabbing the id of the question. So I moved the b-modal to that div and it worked. Thank you for the help.
<div class="card mb-3" v-for="(question, index) in engagement.questions" :key="index">
<div class="card-header">
<div class="h6 m-0 justify-content-between d-flex">
<router-link class="btn btn-sm btn-primary mr-3" to="#" ><i class="far fa-edit mr-2"></i>Edit</router-link>
<b-btn class="outline-secondary" size="sm" v-b-modal.myQuestion><i class="fas fa-trash"></i><span class="ml-2">Delete</span></b-btn>
</div>
</div>
<div class="card-body bg-light d-flex justify-content-between">
<div class="h4 mr-5 text-left">
{{ question.question }}
</div>
<div class="ml-5 d-flex align-self-center">
<span class="font-weight-bold mr-2">Answered: </span>
<input class="mt-2" type="checkbox" v-model="question.answered">
</div>
</div>
<!-- this is the modal for deleting a question -->
<b-modal id="myQuestion" ref="myModalQuestion" hide-footer title="Delete Question">
<div class="d-block text-left">
<h5>Are you sure you want to delete question?</h5>
<br>
<p><strong>*Warning:</strong> Can not be undone once deleted.</p>
</div>
<div class="d-flex">
<b-btn class="mt-3" variant="danger" #click="hideModal">Cancel</b-btn>
<b-btn class="mt-3 ml-auto" variant="outline-success" #click="deleteQuestion(engagement, question.id)">Confirm</b-btn>
</div>
</b-modal>
</div>

Collapse using Transition Vue

I would like to use Vue's collapse in my code, but I have an error.
[Vue warn]: <transition-group> children must be keyed: <p>
My component:
<template xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<section style="background-color: #dedede;">
<div class="container-fluid">
<div class="Consult-faq container">
<div class="row">
<div class="col-sm-12">
<h2>Cursos</h2>
<a v-for="(course,id) in courses" v-on:click="course.show = !course.show">
<a v-on:click="show = !show">
<div class="col-xs-12" style="border-bottom: solid;border-bottom-color: #999999;border-bottom-width:1px ">
<div class="col-xs-12">
<h4>
<i v-if="course.show" class="fa fa-plus-square text-right" aria-hidden="true"/>
<i v-else class="fa fa-minus-square text-right" aria-hidden="true"/>
{{course.text}}
</h4>
</div>
</div>
<transition-group name="fade">
<p v-if="show">
<div class="col-xs-12">
<article v-for="n in 2" class="Module-content">
<div class=" col-sm-12 col-md-6" style="position: relative;">
<div v-for="(course, index) in course.courses">
<course-card v-if="index % 2 == n - 1" :course="course"></course-card>
</div>
</div>
</article>
</div>
</p>
</transition-group>
</a>
</a>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
export default{
props : [
'courses'
],
data(){
return {
show: false
}
},
mounted() {
console.log(this.courses)
}
}
</script>
So, I'd like to know to collapse item per item. Like this in image.
When I click to expand, all courses expand or close all courses close.
Transition is irrelevant here (though you can get rid of that warning by using transition instead of transition-group, because the transition is only acting on a single node, not a group.)
Right now you're depending on a single variable show to control all of the elements' visibility, so they will all respond to clicks on any of them:
<a v-on:click="show = !show">
<p v-if="show" >
You need individual variables for each element if you want them to expand/collapse separately. You partially did this already, just change the remaining instances of show with course.show and you should be good to go.
(Probably want to clean up that nested <a> within <a> while you're at it; you can just remove the inner one.)
I solved this using vue-resource, I was using Guzzle in Laravel and require data in Controller make this not reactive. And I solved this problem using vue-resource in component.

Resources