oliverbusk

Member Since 2 Years Ago

Experience Points
13,590
Total
Experience

1,410 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
88
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 3
13,590 XP
Apr
16
1 month ago
Activity icon

Replied to Being Very Explicit Versus Trying To Keep Things Tidy

Perhaps just keeping the regulations table with both a flag and type column (and just have the flag column nullable). And then just rely on scopes when retreiving data?

Apr
15
1 month ago
Activity icon

Replied to Being Very Explicit Versus Trying To Keep Things Tidy

Thanks, Martin! You hit the question right on the head. I am also leaning towards this solution more (just having one regulations table, and then control what type of regulation by having a type column).

The only concern I have, is for RentRegulation there can be different types of regulations. So a rent can be regulated due to the following stuff (all regulated by law):

  • Increase in inflation
  • Renovating the lease
  • Agreement with the tenant that rent should increase

And that is why I have theflag column mentionde for rent regulations. I am not quite sure how I can overcome this by combining all sort of regulations.

My main concern is when I need to retrieve all of this data / persisting, this solution will force me to apply scopes every time I need to access regulations.

Activity icon

Started a new Conversation Being Very Explicit Versus Trying To Keep Things Tidy

I am building a small system to control my rental properties. In this system, I want to be able to capture any regulations that can happen to a lease. A regulation can happen for:

  • The rent amount
  • The prepaid rent amount
  • The prepaid deposit amount

I am thinking on how I can structure this. I have a Lease model with leases table (simplified):

id | name       | address        | rent | prepaid_rent_amount | prepaid_deposit_amount
1  | Unit no. 1 | Highland Drive | 1000 | 3000                | 3000

In order to capture if any regulation has happened on the above three parameters (rent amount, prepaid rent or prepaid deposit), I need to store this in a database. The information needed to be capture from these parameters are almost identical:

//Regulation in rent
 - lease_id
 - amount
 - date
 - flag

//Regulation in prepaid rent
 - lease_id
 - amount
 - date

//Regulation in prepaid deposit
 - lease_id
 - amount
 - date

Solution 1

I was thinking to create a model/table for each parameter, and simply just store data relevant for each regulation in the corresponding table:

  • RentRegulation
  • PrepaidRentRegulation
  • PrepaidDepositRegulation

I think the benefits of this solution is that the data is separated, however it feels like it is bloating my codebase.

Solution 2

Instead of creating three models/tables to store the above information in, I was thinking to just create one model:

  • LeaseRegulation

An inside this model, simply have a column called type. The value for this column would then control what kind of regulation we were talking about (e.g. RentRegulation)

What are the best practices here? I can see the benefits of both solutions, but I kind of like to keep things tidy.

Apr
10
1 month ago
Activity icon

Replied to Seeding - Laravel Model Factories With 3 Level Relationship

Can you please elaborate on what the issue is with the naming of the relationships?

Apr
09
1 month ago
Activity icon

Started a new Conversation Seeding - Laravel Model Factories With 3 Level Relationship

I am currently building a system to manage my rental properties. I have a model that holds the properties, and each property can have many leases.

In order to bill the leases, I have a model called Invoice which belongs to a Lease. Further, an invoice will have many InvoiceLine

//Property.php
public function leases()
{
        return $this->hasMany(Lease::class);
}

//Lease.php
public function invoices(){
        return $this->hasMany(Invoice::class);
}

//Invoice.php
public function lines()
{
        return $this->hasMany(InvoiceLine::class);
}

I am trying to set up seeding for this setup:

Property::factory()
   ->count(1)
   ->has(
   Lease::factory()
      ->count(2)
      ->hasInvoices(1) // Where to create "Invoice Lines"?
   )
   ->create();

Now, as you can see, when running this seeding I only create an invoice - but no invoice lines.

How can I seed an invoice with invoice lines that belongs to a Lease?

For reference, this is how the factory classes looks for Invoice and Invoice Line:

//InvoiceFactory.php
return [
    'tax' => 0,
    'total' => 25000,
];
//InvoiceLineFactory.php
return [
    'description' => 'Rent for April',
    'tax' => 0,
    'total' => 25000,
];
Apr
08
1 month ago
Activity icon

Awarded Best Reply on Nested Route Naming / Convention

Thanks Martin! I think this might be a better way for me. Still not quite sure how to include the Chargesstill.

Is the below a good way? Since a Charge belongs to a lease, and cannot exists without being bound to a lease.

// web.php
//Property
Route::resource('properties', PropertyController::class);

//Lease
Route::resource('properties.leases', PropertyLeaseController::class)->shallow();

//Charge
Route::resource('leases.charges', LeaseChargeController::class)->shallow();

Just to clarify on the structure of the controllers - each controller will exist in the "main controllers" folder:

app/Http/Controllers/PropertyController.php
app/Http/Controllers/PropertyLeaseController.php
app/Http/Controllers/LeaseChargeController.php

And then the views:

resources/views/properties/...
resources/views/leases/...
resources/views/charges/...
Mar
20
1 month ago
Activity icon

Replied to Naming Of Models And Tables

Good point! Especially about the option to just make the "Charge" polymorphic - didn't think about that.

I think I might also just be overthinking the features that might be introduced to the system in the future.

Activity icon

Started a new Conversation Naming Of Models And Tables

Hey there

I am currently building a system to manage my rental properties, and I am in a bit of a doubt when it comes to naming conventions...

Suppose I have the below setup

  • Properties
  • Leases (A lease belongs to a property)
  • Tenants (A tenant belongs to a lease)
  • Charges (A charge belongs to a lease)

I have currently named it like this:

Model Name | Database Table Name | Controller Name
-----------|---------------------|-----------------------------
Property   | properties          | PropertyController
Lease      | leases              | LeaseController
Tenant     | tenants             | LeaseTenantController
LeaseCharge| lease_charges       | LeaseChargeController

Now I haven't really given much thought into how I should name these things. But looking at the above, I can now see that I am not following one clear convention.

My question here is, how models/tables/controllers should be named, when they are related to another model.

For example both Tenant and Charge belongs to a lease (and can only exist if they have a lease_id), but should this be made explicit in the naming of the model, database and controllers? Or can these nouns stand alone? E.g.:

Model Name | Database Table Name | Controller Name
-----------|---------------------|-----------------------------
Property   | properties          | PropertyController
Lease      | leases              | LeaseController
Tenant     | tenants             | TenantController
Charge     | charges             | ChargeController
Mar
19
1 month ago
Activity icon

Replied to Nested Route Naming / Convention

Great! What about the naming/structure of the controllers and view files? I guess if I utilize the shallow nested ressources, it makes sense to have a view folder for each model:

../properties
../leases
../charges

But what about the controllers? Should they "know" about each other, like:

PropertyController
PropertyLeaseController
PropertyLeaseChargeController

or

PropertyController
LeaseController
ChargeController
Activity icon

Replied to Nested Route Naming / Convention

But what about the view files structure? Where to place the views for Lease and Charge? Under the properties folder as sub-folders?

These long names PropertyLeaseChargeController seems a bit off to me?

But since a Lease cannot exist without belonging to a Property, and a Charge cannot exist without belonging to a Lease, it might be very explanatory to have the long names...

Activity icon

Replied to Nested Route Naming / Convention

Thanks Martin! I think this might be a better way for me. Still not quite sure how to include the Chargesstill.

Is the below a good way? Since a Charge belongs to a lease, and cannot exists without being bound to a lease.

// web.php
//Property
Route::resource('properties', PropertyController::class);

//Lease
Route::resource('properties.leases', PropertyLeaseController::class)->shallow();

//Charge
Route::resource('leases.charges', LeaseChargeController::class)->shallow();

Just to clarify on the structure of the controllers - each controller will exist in the "main controllers" folder:

app/Http/Controllers/PropertyController.php
app/Http/Controllers/PropertyLeaseController.php
app/Http/Controllers/LeaseChargeController.php

And then the views:

resources/views/properties/...
resources/views/leases/...
resources/views/charges/...
Activity icon

Started a new Conversation Nested Route Naming / Convention

I have the below three models:

  • Property
  • Lease
  • Charge

The relationship are as following:

  • A property can have many leases (a lease belongs to a property)
  • A lease can have many charges (a charge belongs to a lease)

I am trying to figure out how I should structure my folders and route naming. The controllers are placed like the below:

app/Http/Controllers/PropertyController
app/Http/Controllers/LeaseController
app/Http/Controllers/ChargeController

In my routes file, I have just defined them like this:

//Properties
Route::resource('properties', PropertyController::class);

//Leases
Route::resource('properties.leases', LeaseController::class);

//Charges
Route::resource('properties.leases.charges', ChargeController::class);

The .blade files are structured like this:

resources/views/properties/...
resources/views/leases/...
resources/views/charges/...

I find the above a bit confusing, as using a setup like this, I have to write long route links:

properties.index
properties.leases.show
properties.leases.charges.create // <-- This is quite long and looks awkward in my IDE I think

Is this the preferred way of structuring files/controllers?

Mar
15
2 months ago
Activity icon

Started a new Conversation Naming "nested" Relationships

Hi there

I have a doubt in regards to how I am naming my models, table names etc. in Laravel 8.

I have a small system, that track my rental properties. I refer to my rental units as "Leases". The setup is as per below:

  • A Lease can have one tenant (payer) (Tenant model)
  • A Lease can have different costs associated with it, and these costs might need to be charged in different periods (LeaseChargePeriod model)
  • A LeaseChargePeriod can have multiple charges (costs) (LeaseCharge)

Which ultimately ends up looking like the below:

enter image description here

For some reason, I find these names kind of awkward, but I am not sure what the convention is here. An alternative could be to have:

  • Leases

  • Tenants

  • Periods

  • Charges

But again - all three models (tenants, periods and charges) is "under" a lease.

Am I just overthinking this?

Mar
13
2 months ago
Activity icon

Started a new Conversation Structuring Rent Charges (fixed And Variable)

I am trying to create a small platform to control my rental properties (rent payments).

I have the below setup:

  • Lease (rental units)
  • Lease Charges (the actual rent of each rental unit)

The case is, each of my rental units will have some costs (rent) associated with them. I refer to this as charges.

Now the charges are usually the same month-to-month, but it might happen that I need to charge something extra on a specific unit:

  • as a one time charge
  • as a recurring charge over X number of months

Now, I don't want to add the same fixed costs every month, so I have created the below setup:

Below is the database for the leases:

id | address
1  | Hw Avenue 15
2  | Woodland Rd 1

And for the lease_charges:

id | lease_id | amount | description
1  | 1        | 100000 | Monthly rent
2  | 1        | 20000  | Electricity
3  | 2        | 500000 | Monthly rent (all included)

Then in my codebase, I can simply get all the fixed charges for a specific lease using a hasMany relationship on the Lease model:

$lease->charges; 

The problem here is I cannot create "one time charges" or charges that should only be applicable for X number of months. My current idea is to change the database table lease_charges to:

id | lease_id | amount | description                  | fixed | period
1  | 1        | 100000 | Monthly rent                 | 1     |
2  | 1        | 20000  | Electricity                  | 1     |
3  | 2        | 500000 | Monthly rent (all included)  | 1     |
4  | 1        | 80000  | Broken sink                  | 0     | 04.2021, 05.2021, 06.2021
5  | 1        | 80000  | Extra water                  | 0     | 04.2021

So in the above, id 4 is a charge that should be applied to the invoices in April, May and June. Id 5 is a one time charge that should only be applied to the April invoice.

Is this setup a good practice? I am wondering how this setup would work - also how I could fetch the right charges for a specific month.

Mar
12
2 months ago
Activity icon

Replied to Rent Frequency

Very good point in regards to up, due and overdue payments - I would definetely need to be able to check for that.

I agree, that it might be easier to simply just move it to the 1st of the month, if the date is after the 28th. Thanks!

Activity icon

Replied to Rent Frequency

Also, @martinbean - what if the anchor date is set to e.g January 31, 2021 and the rent frequency is 1 time every month - how would that work for months where there are not 31 days?

Mar
11
2 months ago
Activity icon

Replied to Rent Frequency

I wanted to utilize some sort of admin package (E.g. Nova), to show a list of my rental units and when the rent was due. Once I collected the rent, I want to mark them individually as "Paid" (for that specific payment schedule - as rent is collected again on the next payment schedule, and thus the unit should show up again)

Activity icon

Replied to Rent Frequency

That's an interesting approach. How would this work with code though?

For example, if I want to set up a payment schedule for the 15th for every month:

id | name                    | rent_frequency | rent_frequency_count | anchor_date
1  | Highland Rd 15   | month                | 1                                       | 15.04.2021

What is the best way to actually get this information from the Lease model? With a accessor?

For example, I could imagine I would need to print out the payment schedule:

public function getPaymentDateAttribute($value)
{
     //....
}

Or just declare some methods on the model? If I need to get the next payment date:

public function NextPaymentDate()
{
     //....
}
Activity icon

Started a new Conversation Rent Frequency

Hi there

I am building a small system to manage my rental units. I have a few units that I lease to different tenants. A rental unit can have different payment schedules - for example:

  • Once every month (on the 1st)
  • Once every month (on the XX day)
  • Once every quarter
  • Once per year

Currently, my setup looks like this and can only handle the first case (once every month on the first):

 Schema::create('leases', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('rent_frequency')->default('monthly');
            $table->timestamps();
});

My first thought was to just set the rent_frequency to e.g. "yearly" or "quarterly", and then perhaps just parse it with Carbon\Carbon, but I am not sure if that is a good way.

Can anyone help me on how I can make the payment scheduling more flexible, to allow for the above scenarios?

Feb
03
3 months ago
Activity icon

Replied to Register Custom Notification Channel From Array

Awesome - thank you so much!

Activity icon

Replied to Register Custom Notification Channel From Array

@piljac1, first of all - what a wonderful reply. I really appreciate you taking your time writing this. It helped me a lot - not only with my problem - but also to increase my understanding of the Laravel framework in general. I did not know about the custom service provider. Awesome!

I just have one question - what if I want to add more custom channels, would I then have to duplicate the below code (and replace msteams with the custom channel name)?

public function register()
{
    \Illuminate\Support\Facades\Notification::resolved(function(ChannelManager $service){
        $service->extend('msteams', function($app){
            return $app->make('msteams');
        });
    });
\Illuminate\Support\Facades\Notification::resolved(function(ChannelManager $service){
        $service->extend('skype', function($app){
            return $app->make('skype');
        });
    });
}

Or can I pass an array to extend() and make?

Feb
02
3 months ago
Activity icon

Started a new Conversation Register Custom Notification Channel From Array

I have created a custom notification channel in Laravel, by following the documentation.

The custom channel class is called TeamsBotChannel, and I can easily use it by doing the below:

public function via($notifiable){
  
    return [TeamsBotChannel::class];

}

Now, in my database, I store my users notification preferences in a table. In the via method, I want to query these and return them, so users can decide what channels they want to be notified on.

This can look like the below:

public function via($notifiable){
    
    $channels = $notifiable->channels->toArray();
    //$channels return an array: ['email', 'slack', 'msteams']
     
}

Now my problem is, how can I link the msteams value to my custom channel TeamsBotChannel? I can easily just return email and slack in the via method, but for a custom channel, I need to reference the class.

Jan
31
3 months ago
Activity icon

Replied to Storing Notification Settings Per User

I was thinking, does it have to be a "many-to-many" relationship? What about a one to many (a user can have many notification types):

notification_types:

id | user_id | type            | channel
1  | 1       | todo_assigned   | slack, email
3  | 1       | project_created | email 

The channel column is just a comma separated string that stores the different channels for the specific user and type?

Then simple in my user model:

//User.php
public function notificationTypes()
{
	return $this->hasMany(NotificationType::class);
}
Jan
29
3 months ago
Activity icon

Replied to Storing Notification Settings Per User

Thank you for replying @martinbean! So if I understand correctly, it will correspond to something like the below:

Pivot table (many-to-many) notification_user

user_id      | notification_type_id
1            | 1  
1            | 2

notification_types:

id | type            | channel
1  | todo_assigned   | slack
2  | todo_assigned   | email
3  | project_created | email 

In the above scenario, user.1 have the below notification enabled:

  • New to do has been assigned => notify via slack and e-mail
  • New project has been created => notify via e-mail

Is that correct? In the first case (both Slack & E-mail), how to check for this in the Notification class?

Activity icon

Started a new Conversation Storing Notification Settings Per User

Hi everyone!

I am developing a fairly simple application, where I want my users to be able to subscribe to notifications. So the system should:

  • Send notifications when a certain event they are subscribed to happens.
  • Send notifications to the channels they have selected (email or slack)

Below is an example of different notifications they each user can subscribe to.

enter image description here

I am wondering how to do this using Laravel. My first idea was to:

  1. Create a notifications JSON column on the users table, and store it like (probably using the learnings from the Managing Mass User Settings lesson.)
{
  "todo": {
    "assigned": [
      {
        "email": true,
        "slack": true
      }
    ],
    "mentioned": [
      {
        "email": true,
        "slack": true
      }
    ]
  },
  "project": {
    "created": [
      {
        "email": true,
        "slack": true
      }
    ]
  }
}

However, I am unsure if this is good practice. Further, I am also a unsure on how to actually send out the notifications dynamically.

For sending it out, I want to use Laravels notification system:

Notification::send($user, new TodoCreated($todo));

I am not sure if this is the best way, or if it makes more sense to use an Event/Listener setup? A

Also, can I utilize the via() method on the Notification class to dynamically specify the channels according to the user settings?

Any input would be greatly appreciated.

Jan
28
3 months ago
Jan
20
3 months ago
Activity icon

Started a new Conversation Laravel RESTful Api - Best Practice For Query Params

I have a simple website running Laravel Jetstream with Teams enabled. On this website, you can create different "to-do tasks", which are owned by a team. I have a model called Task.

I am trying to create a public facing API, so my users can query their tasks from their own applications. In my routes/api.php file, I have added this:

Route::middleware('auth:sanctum')->group(function(){
    Route::apiResources([
        'tasks' => \App\Http\Controllers\API\TaskController::class,
    ]);
});

And then in the TaskController, I have only begun coding the index method:

/**
 * Display a listing of the resource.
 * @queryParam team int The team to pull tasks for.
 * @return \Illuminate\Http\Response
*/
public function index()
{

   if(request()->team){
        $tasks = Task::where('team_id', request()->team)->get();
        return TaskResource::collection($tasks);
   }

   return response([
        'status' => 'error',
        'description' => "Missing required parameter `team`."
   ], 422);
      
}

Now this works fine. I can make a GET request to https://example.org/api/tasks?team=1 and successfully get all the tasks related to team.id = 1.

However, what if I want to include multiple query parameters - some required, others only optional. For example, if I want to let users access all tasks with a given status:

https://example.org/api/tasks?team=1&status=0

What is the best practices around this? As I can see where things are going now, I will end up with a lot of if/else statement just to check for valid parameters and given a correct error response code if something is missing.

Activity icon

Started a new Conversation Jetstream/Sanctum - Change Tokenable Model

In Laravel Jetstream, the API Tokens are bound to the User model by:

class User extends Authenticatable
{
     use HasApiTokens; //This enables API on the user model.
     ...
}

However, I am also using Jetstream with Teams enabled. I wish to change so the API tokens are not bound to a specific user, but rather a specific team. This means that if an user have API tokens for a specific team, and he chooses to delete his account, the API tokens are still valid as they would be bound to a team.

I see in Jetstream, that the ApiTokenManager is handling all of this, but it is all bound to $this->user. Further, this class is not published when publishing the assets.

Any idea on how I can change the default model to be Team instead of User?

Alternatively, how can I publish the ApiTokenManager from the vendor folder?

Jan
19
3 months ago
Activity icon

Replied to Integrating Different Services To Laravel

Yes I read about Socialte, but I am not sure I understand it's usecase 100%. As I don't want my users to be able to login to my application using Socilate, but rather they should be able to integrate 3rd party applications to the team they are a member of.

So once user.1 is logged in, he can go to his team site and add a Slack integration (once this is added, the slack integration will have "access" to the "Team instance" and not the "User instance").

My doubt here is if I can use Socialite for this, and further how to store the integrations in a database.

Activity icon

Started a new Conversation Integrating Different Services To Laravel

Hi there

I am currently building a to-do application (for practice), and I am trying to add integrations to other services such as Slack.

Imagine that I have the below button on a team profile /teams/1/integrations:

enter image description here

When the user clicks on Add to Slack, it will open Slack authentication flow in a pop-up, and ask the user to authenticate using their Slack credentials.

The Slack integration now have access to the team.1 instance on my website.

What I essentially want is for users to be able to integrate multiple services: Slack, GitHub, Figma etc, and bind these to teams.

I am having some problems conceptualizing this, however. Do I need to connect to each of these services' Oauth2 flow? And what do I essentially store in my own database, for each user?

I am using Laravel Jetstream with teams enabled.

Jan
14
4 months ago
Activity icon

Started a new Conversation Loading A Livewire Component Inside A Modal

Description

I am trying to dynamically load a Livewire component inside a modal, using Livewire. I can successfully load the HTML content in the modal, but any Javascript on the "target" component is not executed.

Exact steps to reproduce

<!-- index.blade.php -->
<a onclick="showTask(1)">Open task #1</a>
@includeWhen($openTask, 'partials.tasks._task_modal')
//Index.php 
function showTask(int $taskId){
        $this->managingTask = true;
        $this->openTask = Task::firstWhere('id', $taskId);
}

So in the above code, when a user clicks the a tag, it will open the modal, placed in:

<!-- _task_modal.blade.php -->
<x-jet-dialog-modal wire:model="managingTask">
    <x-slot name="content">
        @livewire('tasks.show', ['task' => $openTask])
    </x-slot>
</x-jet-dialog-modal>

As you can see, the modal component simply refers to another Livewire component called tasks.show. Inside this, I have the following in the view file:

<!-- show.blade.php -->
<a onclick="test()">Test</a>
@push('scripts')
    <script type="text/javascript">
        function test(){
            alert("It works!")
        }
       document.addEventListener('livewire:load', function () {
          console.log("Livewire Loaded");
      });
  </script>
@endpush

Now, when clicking on the a link inside the show.blade.php Livewire component, I get the following error:

Uncaught ReferenceError: test is not defined

Further, I do not see the "Livewire Loaded" in my console.

Context

  • Livewire version: 2.3.6
  • Laravel version: 8.12
  • Browser: Chrome
Activity icon

Started a new Conversation Turbolinks And Livewire Loads Javascript Multiple Times

Hi there

I am trying to get Turbolink to work together with Livewire, but with little luck. For some reason, when using either livewire:load or turbolinks:load as my event listener, the javascript is fired off multiple times if a user visits the page more than once. See the below GIF for example:

Skarmoptagelse-2021-01-14-kl.-10.26.05.gif

This is my setup:

//app.blade.php
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- Styles -->
    <link rel="stylesheet" href="{{ mix('css/app.css') }}">

    @livewireStyles
    <style>
        [x-cloak] {
            display: none;
        }
    </style>

    <!-- Scripts -->
    <script src="{{ mix('js/app.js') }}" data-turbolinks-track="reload" data-turbolinks-eval="false" defer></script>
    @livewireScripts
    @stack('scripts')

</head>
<body>
<div id="root" x-data>
    <div class="main">
            <div class="content">
                    {{ $slot }}
            </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/gh/livewire/[email protected]/dist/livewire-turbolinks.js" data-turbo-eval="false" data-turbolinks-eval="false"></script>

</body>

I have further installed Turbolinks with NPM, and included it in my app.js file:

//app.js
var Turbolinks = require("turbolinks")
Turbolinks.start()

The page in the video contains this:

<!-- show.blade.php -->
<div>
   @foreach($actions as $action)
     <a wire:click="selectAction({{$loop->index}})">{{$action->name}}</a>
   @endforeach
</div>
@push('scripts')
    <script type="text/javascript">
        var actionSelected = false;

        document.addEventListener('livewire:load', function () {
            var numberOfActions = @this.get('actions').length;

            window.addEventListener('actionSelected', event => {
                actionSelected = true;
                drawAction(event.detail.schema);
            });

            function drawAction(schema) {

                console.log(schema);
            
            }
        });

    </script>
@endpush

The selectAction method, looks like this:

//Show.php
public function selectAction(int $index)
{
        $this->action = $this->actions->slice($index, 1)->first();
        $this->schema = $this->setSchema(); //Returns JSON

        $this->dispatchBrowserEvent('actionSelected', ['schema' => $this->schema]);
}

What am I doing wrong? Why does it fire the drawAction javascript method multiple times, when "revisitting" the page?

Jan
13
4 months ago