John Davidson

php - Laravel 8 component button "onclick" directly activating on load not on click

0 comments
Message:


I'm using a component with a public function UnlockAdvertisement(int $id)
In this component I have a button with the onclick function used.
But this function gets triggered everytime the component gets loaded, not when the button gets clicked.
It's like reversed?!


Thanks ahead for your help


The component is used via a yield


@section('advertisementView')
<div class="container">
<x-advertisement.advertisement-view-master :id="$id"/>
@yield('advertisementViewForUnlock')
</div>
@endsection

This is the component in the yielded blade:


@extends('Advertisements.AdvertisementView')

@section('advertisementViewForUnlock')
<div class="container">
<x-management.unlock-advertisement :id="$id"/>
</div>
@endsection

and this is the actual component


<div>
<div class="col">
<div class="row mt-2">
<hr/>
</div>
<div class="col">
<button type="button" class="btn btn-success me-1"
onclick=" {{ $UnlockAdvertisement($AdvertisementId) }}">Freischalten</button>
<button type="button" class="btn btn-danger">Ablehnen</button>
</div>
</div>
</div>

The function that gets executed at site load not at button click


    public function UnlockAdvertisement(int $id)
{
$tempAdvertisement = Advertisement::where('id', $id)->first();
$tempAdvertisement->unlocked = true;
$tempAdvertisement->save();

return redirect()->route('management-dashboard');
}


My Answer:
To create a button component in Laravel 8 using Blade components, you can follow these steps:

1. Create a new Blade component for the button:
bash
php artisan make:component Button


This will create a new Blade component file in the `resources/views/components` directory called `button.blade.php`.

2. Open the `button.blade.php` file and add the following code to create a button component:
php



In this code, we are using the `$attributes` variable to merge any additional attributes passed to the component with the default class attribute. The `$slot` variable is used to render the content inside the button component.

3. To use the button component in your views, you can include it like this:
php

Click me



This will render a button with the text "Click me" and the default styling defined in the component.

You can customize the button component further by adding more classes or attributes to the button element in the `button.blade.php` file. You can also pass additional attributes to the component when including it in your views.

Rate this post

4 of 5 based on 9763 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us