esorone

Member Since 4 Years Ago

Experience Points
13,890
Total
Experience

1,110 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
89
Lessons
Completed
Best Reply Awards
3
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,890 XP
Apr
12
5 days ago
Activity icon

Replied to Why I Can't Play Any Videos In Laracasts ?

I’m just able to play videos. Did you try another browser?

Apr
08
1 week ago
Activity icon

Replied to Get Single Role From User

Goodmorning..

Im not into morph.. but what I did notice is that I don't see a roles.user_id in your migration file. The columns are: id, name, guard_name and no user_id

And basically this is what the error tells. So I would start to add the user_id to the roles table.

Apr
06
1 week ago
Activity icon

Replied to Get Single Role From User

Hello,

Could you share your migration files as well? So we can see if there is an actual column? Because in your database structure I see: roles.id and role_user.user_id. So I don't see roles.user_id. Just ot make sure if the naming convention is being followed.

Kr

Apr
05
1 week ago
Activity icon

Replied to Call Another Component

Of course.. I have a modal in the blade view and as you mention I try to use the second button to redirect to another modal.. I try to refactor the code a little bit, so there are some changes compared to my initial code. Underneath the two blade files and the two livewire components

My navigation-menus.blade. This one includes a modal

<div class="p-6">
    <div class="flex items-center justify-end px-4 py-3 text-right sm:px-6">

{{--        The two buttons underneath--}}

        <x-jet-button wire:click="createShowModal">
            {{ __('Create Nav Menu') }}
        </x-jet-button>
        <x-jet-button wire:click="shortCut" class="bg-green-500">
            {{ __('Create Page') }}
        </x-jet-button>
    </div>

    {{-- The data table --}}
    <div class="flex flex-col">
        <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Icon</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Type</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Sequence</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Label</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Url</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                </th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @if ($data->count())
                            @foreach ($data as $item)
                            <tr>

                                <td class="px-6 py-2">
                                    <x-tabler icon="{{$item->iconname}}" class="h-6" />
                                </td>
                                <td class="px-6 py-2">{{ $item->type }}</td>
                                <td class="px-6 py-2">{{ $item->sequence }}</td>
                                <td class="px-6 py-2">{{ $item->label }}</td>
                                <td class="px-6 py-2">
                                    <a class="text-indigo-600 hover:text-indigo-900" target="_blank"
                                        href="{{ url( $item->slug )}}">
                                        {{ $item->slug }}
                                    </a>
                                </td>
                                <td class="px-6 py-2 flex justify-end">
                                    <x-jet-button wire:click="updateShowModal({{ $item->id }})">
                                        {{ __('Update') }}
                                    </x-jet-button>
                                    <x-jet-danger-button class="ml-2" wire:click="deleteShowModal({{ $item->id }})">
                                        {{ __('Delete') }}
                                        </x-jet-button>
                                </td>
                            </tr>
                            @endforeach
                            @else
                            <tr>
                                <td class="px-6 py-4 text-sm whitespace-no-wrap" colspan="4">No Results Found</td>
                            </tr>
                            @endif
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <br />
    {{ $data->links() }}

    {{-- Modal Form --}}
    <x-jet-dialog-modal wire:model="modalFormVisible">
        <x-slot name="title">
            {{ __('Navigation Menu Item') }}
        </x-slot>

        <x-slot name="content">
            <div class="mt-4">
                <x-jet-label for="label" value="{{ __('Label') }}" />
                <x-jet-input wire:model="label" id="label" class="block mt-1 w-full" type="text" />
                @error('label') <span class="error">{{ $message }}</span> @enderror
            </div>
            <div class="mt-4">
                <x-jet-label for="iconname" value="{{ __('Icon Name lowercase') }}" />
                <div class=" flex w-full">
                    <x-jet-input wire:model="iconname" id="iconname" class="w-full" type="text" />
                    <div
                        class=" w-1/5  bg-yellow-400  text-gray-800 font-bold uppercase border-yellow-500 flex justify-center content-center ">
                        <x-tabler icon="{{$icon}}" class="h-6 mt-2 font-extrabold" />
                    </div>
                </div>
                <a href="https://tablericons.com/" class=" text-xs ml-2">Search Icons</a>
            </div>
            <div class="mt-4">
                <x-jet-label for="slug" value="{{ __('Slug') }}" />
                <div class="mt-1 flex rounded-md shadow-sm">
                    <span
                        class="inline-flex items-center px-3 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-gray-500 text-sm">
                        flows.test/
                    </span>
                    <select wire:model="slug"
                        class="form-input flex-1 block w-full rounded-none rounded-r-md transition duration-150 ease-in-out sm:text-sm sm:leading-5">
                        <option value="">-- Select a Slug --</option>
                        @foreach (App\Models\NavigationMenu::slugNameList() as $item)
                        <option value="{{ $item }}">{{ $item }}</option>
                        @endforeach
                    </select>
                </div>
                {{-- <a href="{{ route('create') }}"> create</a> --}}
                @error('routeName') <span class="error">{{ $message }}</span> @enderror
            </div>


            <div class="mt-4">
                <x-jet-label for="sequence" value="{{ __('Sequence') }}" />
                <x-jet-input wire:model="sequence" id="sequence" class="block mt-1 w-full" type="text" />
                @error('sequence') <span class="error">{{ $message }}</span> @enderror
            </div>
            <div class="mt-4">
                <x-jet-label for="sequence" value="{{ __('Type') }}" />
                <select wire:model="type"
                    class="block appearance-none w-full bg-gray-100 border border-gray-200 text-gray-700 py-3 px-4 pr-8 round leading-tight focus:outline-none focus:bg-white focus:border-gray-500">
                    <option value="SidebarNav">SidebarNav</option>
                    <option value="TopNav">TopNav</option>
                </select>
            </div>
        </x-slot>

        <x-slot name="footer">
            <x-jet-secondary-button wire:click="$toggle('modalFormVisible')" wire:loading.attr="disabled">
                {{ __('Nevermind') }}
            </x-jet-secondary-button>

            @if ($modelId)
            <x-jet-button class="ml-2" wire:click="update" wire:loading.attr="disabled">
                {{ __('Update') }}
                </x-jet-danger-button>
                @else
                <x-jet-button class="ml-2" wire:click="create" wire:loading.attr="disabled">
                    {{ __('Create') }}
                    </x-jet-danger-button>
                    @endif

        </x-slot>
    </x-jet-dialog-modal>

    {{-- The Delete Modal --}}

    <x-jet-dialog-modal wire:model="modalConfirmDeleteVisible">
        <x-slot name="title">
            {{ __('Delete Page') }}
        </x-slot>

        <x-slot name="content">
            {{ __('Are you sure you want to delete this navigation item?') }}
        </x-slot>

        <x-slot name="footer">
            <x-jet-secondary-button wire:click="$toggle('modalConfirmDeleteVisible')" wire:loading.attr="disabled">
                {{ __('Nevermind') }}
            </x-jet-secondary-button>

            <x-jet-danger-button class="ml-2" wire:click="delete" wire:loading.attr="disabled">
                {{ __('Delete Navigation Item') }}
            </x-jet-danger-button>
        </x-slot>
    </x-jet-dialog-modal>
</div>

My pages.blade Basically I want to have the button on my navigation_menus pointing to the modal on this page

<div class="p-6">
    <div class="flex items-center justify-end px-4 py-3 text-right sm:px-6">
        <x-jet-button wire:click="createShowModal" class="ml-4">
            {{ __('Create') }}
        </x-jet-button>
    </div>
    {{-- The data table --}}
    <div class="flex flex-col">
        <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">

                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Title</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Link</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                    Content</th>
                                <th
                                    class="px-6 py-3 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
                                </th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @if ($data->count())
                            @foreach ($data as $item)
                            <tr>
                                <td class="px-6 py-4 text-sm whitespace-no-wrap">
                                    {{ $item->title }}
                                    {!! $item->is_default_home ? '<span
                                        class="text-green-400 text-xs font-bold">[Default Home Page]</span>':''!!}
                                    {!! $item->is_default_not_found ? '<span
                                        class="text-red-500 text-xs font-bold">[Default 404 Page]</span>':''!!}
                                </td>
                                <td class="px-6 py-4 text-sm whitespace-no-wrap">
                                    <a class="text-indigo-600 hover:text-indigo-900" target="_blank"
                                        href="{{ URL::to('/'.$item->slug)}}">
                                        {{ $item->slug }}
                                    </a>
                                </td>
                                <td class="px-6 py-4 text-sm whitespace-no-wrap">{!!
                                    \Illuminate\Support\Str::limit($item->content, 50, '...') !!}</td>
                                <td class="px-6 py-4 text-right text-sm">
                                    <x-jet-button wire:click="updateShowModal({{ $item->id }})">
                                        {{ __('Update') }}
                                    </x-jet-button>
                                    <x-jet-button class="bg-red-500" wire:click="deleteShowModal({{ $item->id }})">
                                        {{ __('Delete') }}
                                    </x-jet-button>
                                </td>
                            </tr>
                            @endforeach
                            @else
                            <tr>
                                <td class="px-6 py-4 text-sm whitespace-no-wrap" colspan="4">No Results Found</td>
                            </tr>
                            @endif

                        </tbody>
                    </table>


                </div>
            </div>
        </div>
    </div>

    <br />
    {{ $data->links() }}

    {{--    Modal Form--}}
    <x-jet-dialog-modal wire:model="modalFormVisible">
        <x-slot name="title">
            {{ __('Save Page') }} {{ $modelId }}
        </x-slot>

        <x-slot name="content">
            <div class="mt-4">
                <x-jet-label for="title" value="{{ __('Title') }}" />
                <x-jet-input id="title" class="block mt-1 w-full" type="text" wire:model.debounce.800ms="title" />
                @error('title') <span class="error">{{ $message }}</span>@enderror
            </div>
            <div class="mt-4">
                <x-jet-label for="slug" value="{{ __('Slug') }}" />
                <div class="mt-1 flex rounded-md shadow-sm">
                    <span
                        class="inline-flex items-center px-3 border border-r-0 border-gray-300 bg-gray-50 text-gray-500 text-sm">
                        http://flow.test/</span>
                    <x-jet-input wire:model="slug" placeholder="url-slug"
                        class="block  w-full durarion-150 ease-in-out text-sm sm:leading-5" type="text"
                        wire:model.debounce.800ms="slug" />
                </div>
                @error('slug') <span class="error">{{ $message }}</span>@enderror
            </div>
            <div class="mt-4">
                <label>
                    <input type="checkbox" class="form-checkbox" value="{{$isSetToDefaultHomePage}}"
                        wire:model="isSetToDefaultHomePage" />
                    <span class="text-gray-500 text-sm">Set as default homepage</span>
                </label>
            </div>
            <div class="mt-4">
                <label>
                    <input type="checkbox" class="form-checkbox" value="{{$isSetToDefaultNotFoundPage}}"
                        wire:model="isSetToDefaultNotFoundPage" />
                    <span class="text-red-500 text-sm">Set as 404 error Page</span>
                </label>
            </div>
            <div class="mt-4">
                <x-jet-label for="content" value="{{ __('Content') }}" />
                <div class="rounded-md shadow-sm">
                    <div class="mt-1 bg-white">
                        {{--  Ignore, dan kijkt LW er niet naar--}}
                        <div class="body-content" wire:ignore>
                            <trix-editor class="trix-content" x-ref="trix" wire:model.debounce.100000ms="content"
                                wire:key="trix-content-unique-key"></trix-editor>
                        </div>
                    </div>
                </div>
                @error('content') <span class="error">{{ $message }}</span>@enderror
            </div>
        </x-slot>

        <x-slot name="footer">
            <x-jet-secondary-button wire:click="$toggle('modalFormVisible')" wire:loading.attr="disabled">
                {{ __('Nevermind') }}
            </x-jet-secondary-button>

            @if ($modelId)
            <x-jet-button class="ml-2 bg-ccv_gradient-ccv_pur1" wire:click="update" wire:loading.attr="disabled">
                {{ __('Update') }}
            </x-jet-button>
            @else
            <x-jet-button class="ml-2 bg-ccv_gradient-ccv_pur1" wire:click="create" wire:loading.attr="disabled">
                {{ __('Create') }}
            </x-jet-button>
            @endif
        </x-slot>
    </x-jet-dialog-modal>
    <x-delete-modal />



</div>

Livewire NavigationMenus.php (shortcut method)


    public function shortCut()
    {
        $this->emit('createPage');

     //   dd($this->emit('createPage'));
     
    }

output of the dd($this->emit('createPage')); Component = null?

Livewire\Event {#1588 ▼
  #name: "createPage"
  #params: []
  #up: null
  #self: null
  #component: null
}

Pages.php


<?php

namespace App\Http\Livewire;

use Illuminate\Validation\Rule;
use Livewire\Component;
use App\Models\Page;
use Livewire\WithPagination;

class Pages extends Component
{
    use WithPagination;

    public $modalFormVisible = false;
    public $modalConfirmDeleteVisible = false;
    public $slug;
    public $title;
    public $content;
    public $modelId;
    public $isSetToDefaultHomePage;
    public $isSetToDefaultNotFoundPage;

    protected $listeners = ['createPage' => 'createShowModal'];

    public function rules()
    {
        return [
            "title" => "required",
            "slug" => [
                "required",
                Rule::unique("pages", "slug")->ignore($this->modelId),
            ],
            "content" => "required",
        ];
    }

    /**
     * updateTitle LiveWire function
     * updated is keyword + field
     * Runs after any update to the Livewire component's data (Using wire:model)
     * and runs everytime a title is updated
     * @param $value
     */
    public function updatedTitle($value)
    {
        $this->generateSlug($value);
    }

    /**
     * If value is updated
     * Set the boolan. WIth both functions
     * we make sure that just one is checkt homepage vs 404
     * @param $value
     */
    public function updatedIsSetToDefaultHomePage()
    {
        $this->isSetToDefaultNotFoundPage = null;
    }

    /**
     * If value is updated
     * Set the boolan. WIth both functions
     * we make sure that just one is checkt homepage vs 404
     * @param $value
     */
    public function updatedIsSetToDefaultNotFoundPage()
    {
        $this->isSetToDefaultHomePage = null;
    }

    /**
     * Validate rules
     * The Create function
     * hide modal
     * reset data to null
     */
    public function create()
    {
        $this->validate();
        $this->unassignDefaultHomePage();
        $this->unassignDefaultNotFoundPage();
        Page::create($this->modelData());
        $this->modalFormVisible = false;
        $this->resetData();
    }

    /**
     * The mount function
     */
    public function mount()
    {
        // Resets the pagination after reloading the page
        $this->resetPage();
    }

    /**
     * the show function
     * incl a pagination of x
     * @return mixed
     */
    public function show()
    {
        return Page::paginate(5);
    }

    public function update()
    {
        $this->validate();
        $this->unassignDefaultHomePage();
        $this->unassignDefaultNotFoundPage();
        Page::find($this->modelId)->update($this->modelData());
        $this->modalFormVisible = false;
    }

    /**
     * The Delete function
     */
    public function delete()
    {
        Page::destroy($this->modelId);
        $this->modalConfirmDeleteVisible = false;
        $this->resetPage();
    }
    /**
     * Shows the form modal
     * of the create function
     *
     * @return void
     */
    public function createShowModal()
    {
         $this->resetValidation();
         $this->resetData();
         $this->modalFormVisible = true;

    }

    /**
     * Shows the form modal
     * in update mode
     * @param $id
     */
    public function updateShowModal($id)
    {
        $this->resetValidation();
        $this->resetData();
        $this->modelId = $id;
        $this->modalFormVisible = true;
        $this->loadModel();
    }

    /**
     * Show the delete confirmation
     * modal
     * @param $id
     */
    public function deleteShowModal($id)
    {
        $this->modelId = $id;
        $this->modalConfirmDeleteVisible = true;
    }

    /**
     * Load the model (Page) data
     * into component
     */
    public function loadModel()
    {
        $data = Page::find($this->modelId);
        $this->title = $data->title;
        $this->slug = $data->slug;
        $this->content = $data->content;
        $this->isSetToDefaultHomePage = !$data->is_default_home ? null : true;
        $this->isSetToDefaultNotFoundPage = !$data->is_default_not_found
            ? null
            : true;
    }

    /**
     * The data for de modal mapped
     * into this component and with the
     * page::create it is save into the
     * db
     * @return array
     */
    public function modelData()
    {
        return [
            "title" => $this->title,
            "slug" => $this->slug,
            "content" => $this->content,
            "is_default_home" => $this->isSetToDefaultHomePage,
            "is_default_not_found" => $this->isSetToDefaultNotFoundPage,
        ];
    }

    /**
     * Reset the data to null
     * after submitting
     * the form
     */
    public function resetData()
    {
        $this->modelId = null;
        $this->title = null;
        $this->slug = null;
        $this->content = null;
        $this->isSetToDefaultHomePage = null;
        $this->isSetToDefaultNotFoundPage = null;
    }

    /**
     * Generate the right url slug
     * dashed create a - from spaces
     * lower create a lowerCase string
     * @param $value
     */
    private function generateSlug($value)
    {
        $dashed = str_replace(" ", "-", $value);
        $lower = strtolower($dashed);
        $this->slug = $lower;
    }

    /**
     * Unassigns the default home page in the database table
     *
     * @return void
     */
    private function unassignDefaultHomePage()
    {
        if ($this->isSetToDefaultHomePage != null) {
            Page::where("is_default_home", true)->update([
                "is_default_home" => false,
            ]);
        }
    }

    /**
     * Unassigns the default 404 page in the database table
     *
     * @return void
     */
    private function unassignDefaultNotFoundPage()
    {
        if ($this->isSetToDefaultNotFoundPage != null) {
            Page::where("is_default_not_found", true)->update([
                "is_default_not_found" => false,
            ]);
        }
    }

    /**
     * The live wire render function
     *
     * @return
     */
    public function render()
    {
        return view("livewire.pages", [
            "data" => $this->show(),
        ]);
    }
}


Thank for all the help..

Apr
02
2 weeks ago
Activity icon

Replied to Call Another Component

Hello Tykus,

Thanks in the first place!

I updated my code and basically nothing happens :-( But if I add the listener in the "first component" the modal of the first component is opened.

I check the network tab and XHR and nothings happend.

I called my model: Page, Livewire Component: Pages,

But as I starter I going to do another research at Emit as well, but your help is appreciated! Any idea what could be wrong?

Activity icon

Started a new Conversation Call Another Component

Hello all,

Im still learning Livewire and try to build a small CRUD application. Just for learning purposes. Everything's works fine, but now i just want to have an additional button on a component, which should call another model..

I created some stubs to generate default controllers, models and views. Again, works pretty okay

So because I'm using stubs, I have nearly everywhere the same naming convention, and therefor Im running into the problem underneath.

I have two buttons, and with one I create a menu with a modal (createShowModal).. But at the same page I would like to have another button but now an different modal should be opened. Basically the Modal of the pages creation. I guess the code is self explanatory what I try to achieve, but of course not working. I hope someone is able to point me into the right direction.

Kr

        <x-jet-button wire:click="createShowModal">
            {{ __('Create Menu') }}
        </x-jet-button>

        <x-jet-button wire:click="App\Http\Livewire\Pages::createShowModal()" class="bg-green-500">
            {{ __('Create Page') }}
        </x-jet-button>

Activity icon

Replied to Livewire CRUD (user/post)

Please share some codes. Would be easier to help you out instead op guessing ;-)

Mar
23
3 weeks ago
Activity icon

Replied to Create View, Edit View, Delete View In User Interface

Hello,

Why not store the file in a directory and the location of the file in the database. Or use a great package like https://github.com/spatie/laravel-medialibrary

Mar
04
1 month ago
Activity icon

Awarded Best Reply on Update Method When Adding An Additional Field

Hello All,

As promised I post my solution. The suggested series where mainly focussing on many to many.. And app is regarding on to many. But in the end i manage to update the request. Likely is this not the best way to do is, but it did the job. Unfornunately the attach() only works for many to many.

My controller

public function update(Request $request, $id)
    {

        $command = Command::findOrFail($id);
        $command->name = $request->name;
        $command->description =  $request->description;
        $command->update();

        // Remove all fields and add new
        $command->fields()->delete();
        // Save each fields

        if($request->get('field')){
            foreach($request->get('field') as $key => $field)
            {
                $fields = new Fields();
                $fields->command_id = $command->id;
                $fields->field = $field;
                $fields->id = $request->field[$key];
                $fields->save();
            };
        };

        return redirect('/admin/commands')->with('success', 'Command is successfully updated');
    }

Activity icon

Replied to Update Method When Adding An Additional Field

Hello All,

As promised I post my solution. The suggested series where mainly focussing on many to many.. And app is regarding on to many. But in the end i manage to update the request. Likely is this not the best way to do is, but it did the job. Unfornunately the attach() only works for many to many.

My controller

public function update(Request $request, $id)
    {

        $command = Command::findOrFail($id);
        $command->name = $request->name;
        $command->description =  $request->description;
        $command->update();

        // Remove all fields and add new
        $command->fields()->delete();
        // Save each fields

        if($request->get('field')){
            foreach($request->get('field') as $key => $field)
            {
                $fields = new Fields();
                $fields->command_id = $command->id;
                $fields->field = $field;
                $fields->id = $request->field[$key];
                $fields->save();
            };
        };

        return redirect('/admin/commands')->with('success', 'Command is successfully updated');
    }

Mar
03
1 month ago
Activity icon

Replied to Update Method When Adding An Additional Field

Thanks again. The reason why I did not watch the episode 31, is because this is refering to a many to many relationship, And I have just a one to many. A command got many fields, but Fields belong to one command.

But I will follow along and maybe it is wise to refactor the code into a many to many relationship.

I keep you guys posted

Activity icon

Replied to Update Method When Adding An Additional Field

Nearly there. But It create a new records if I change a existing field. But a non existing fields is created as it should. Hope you have some ideas left.

Activity icon

Replied to Update Method When Adding An Additional Field

Sorry, It works almost,

Now new fields are being created.. So adding a field 4 will add an additional field... But when I change field 3 with an different value, a new field is being created.. I would expect that the current field 3 would be updated with a new value.. SO almost solved.

Activity icon

Replied to Update Method When Adding An Additional Field

Thanks!!.

Indeed I just had to change update to updateOrCreate.

For future reference my controller:

   public function update(Request $request, $id)
    {
        $command = Command::findOrFail($id);

        $command->id =  $request->id;
        $command->name =  $request->name;
        $command->description =  $request->description;
        $command->flow_id =  $request->flow_id;
        $command->save();

        foreach ($request->field as $id => $value) {
            $command->fields()->where('id', $id)->updateOrCreate(['field' => $value]);
        }

        return redirect('/admin/commands')->with('success', 'Command is successfully updated');
    }


```
Activity icon

Replied to Update Method When Adding An Additional Field

Hello,

Indeed that's the reason but I was not able to solve it. It quite frustrating that you know you own issue, but cannot solve it :-( I just watch the episode but I think there is still something different . If I do the example of the serie on my own code using Tinkerwell, I receive exact the same error.

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::attach()'

$command = App\Models\Command::find(1);
$command->fields()->attach([1, 2]);

It looks like attach is not possible with a hasmany. So I need a kind of refactor the code. Any ideas?

Kr

Activity icon

Replied to Update Method When Adding An Additional Field

Im working on it, but got the "Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::attach() and the Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::sync();

I will read the docs and comeback :-)

Activity icon

Replied to Update Method When Adding An Additional Field

Hey,

Thanks for you answer!

The save was still at this place, because I was working on the controller. But it still saves. I just tried to change the order to see if it helps.

But for sure (i guess) it is due the fact that update() only updates existing records.

Activity icon

Replied to Mkdir(): Permission Denied

Hello,

Not sure if you actually receive an error. But are you running a webserver, or artisan serve or Valet? If you run a webserver, maybe your group permissions are not accurate.

e.g.

sudo chown -R $USER:_www /path/to/laravel/install

Or check :

https://laracasts.com/discuss/channels/general-discussion/laravel-framework-file-permission-security

Activity icon

Started a new Conversation Update Method When Adding An Additional Field

good afternoon,

I am running into an issue, which I can't solve myself. I have an application where I have form with flexible fields. If I create these then it all works fine. Using livewire I can add and remove fields. I already made great progress thanks to MichalOravec as well. But I proceed and in the end, i failed to proceed myself.

Now I run into the following, if I want to edit a field, then I can only edit the existing fields. If I add a field, then only the already existing fields are saved. Which makes sense given the code below. I have already looked if I could solve it with the fill() method but that did not work. Also workarounds with array_diffs or nested foreach, etc did not solve it.

So my question is, how can I make sure that the extra field is saved?

As a starter my ddd(), purely to show what the fields are I have 3 fields, but only Field1 and Field 2 are being saved. (Exists already in de database, corresponding the ID) But field 3 is not saved. Again which makes sense because of my code, but How can I solve this one?

array:7 [▼
  "_token" => "BmSdIF1Xldth6G8IvJnjfs0JkDnbM4ZR9owLyQ4l"
  "_method" => "PUT"
  "id" => "1"
  "name" => "Git Push"
  "description" => "Voor Git"
  "flow_id" => "1"
  "field" => array:3 [▼
    1 => "Field 1"
    16 => "Field 2"
    17 => "Field 3"
  ]
]

```


Controller:

```

    public function update(Request $request, $id)
    {
        $command = Command::findOrFail($id);

        $command->id =  $request->id;
        $command->name =  $request->name;
        $command->description =  $request->description;
        $command->flow_id =  $request->flow_id;


      foreach ($request->field as $id => $value) {
            $test = $command->fields()->where('id', $id)->update(['field' => $value]);
        }

       $command->save();

        return redirect('/admin/commands')->with('success', 'Command is successfully updated');
    }

Form


  <input type="text" name="field[]"
              class="px-4 py-2 border focus:ring-gray-500 focus:border-gray-900 w-full sm:text-sm border-gray-300 		 
 rounded-md focus:outline-none text-gray-600"
      placeholder="Field {{('Describe ' .$field)}}"> </div>

Command model



<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Command extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description', 'flow_id'];

    public function flow()
    {
       return $this->belongsTo(Flow::class);
    }

    public function fields()
    {
        return $this->hasMany(Fields::class);
    }
}

I hope someone can point me into the right direction.

Kr

Feb
26
1 month ago
Activity icon

Replied to Trying To Get Logic Out Of Blade Nested Relationship

Thanks for some great links!

Activity icon

Replied to Update An Array

Thanks!!,

This works perfectly.. You don't want to know how long I was struggling on this part.

Activity icon

Started a new Conversation Update An Array

Goodafternoon,

I running onto a problem which I cannot solve on my own. I have a form with a flexible amount of field (add a new input field when pressing a button). I manage to submit this form and the fields are stored into the database successfully.

Now I try to extend the CRUD with an update.. And basically I don't have a clue anymore. I cannot craps this one. The value of the last records is being stored on [0],[1] and [2]. I tried numerous methods, but Im at this stage it is more trail and error then that I know what I am doing :-(

Hope someone can shine some light into the darkness

The input of my view

 <div class="flex flex-col">
              <label class="leading-loose">Edit Fields</label>
               @foreach($fields as $field)
                 <input type="text" name="field[]" value="{{$field->field}}">
                @endforeach
 </div>

If I ddd($request->field) I receive the array underneath.

array:3 [▼
  0 => "aaa"
  1 => "bbb"
  2 => "cccc"
]

My Controller part:

    public function update(Request $request, $id)
    {
        $command = Command::findOrFail($id);

        $command->id =  $request->id;
        $command->name =  $request->name;
        $command->description =  $request->description;
        $command->flow_id =  $request->flow_id;
        $command->save();

ddd($request->field);

        foreach ($request->field as $field => $value)
        {
            $command->fields()->update(['field' => $value]);
        }
        return redirect('/admin/commands')->with('success', 'Command is successfully updated');
    }

Fields Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Fields extends Model
{
    protected $fillable=['commands_id', 'field'];

    public function command()
    {
        return $this->belongsTo(Command::class);
    }
}

Command Model


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Command extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description', 'flow_id'];

    public function flow()
    {
       return $this->belongsTo(Flow::class);
    }

    public function fields()
    {
        return $this->hasMany(Fields::class);
    }
}

Kr EsorOne

Feb
24
1 month ago
Activity icon

Replied to Give Your Best Solutions

I’m not the expert over here and I just love building apps for small hobby projects. But because you asked for other solution, I just did category has many posts and post has many content.

Kr

Activity icon

Replied to Show Category List And Related Posts

Hello,

Any errors and are you able to show the controller as well?

Btw: Next to this there are some creat series on this topic.. With these examples, you are able to debug your app quite easily. Just as a tip! I know looking to the series cost time, but you will earn it back for sure.

Activity icon

Replied to Login Fails After Upgrading From 5.8 To Laravel 8

Goodafternoon,

How did you update the application? Or what did you update?

Feb
16
2 months ago
Activity icon

Started a new Conversation Dynamic Menu

Good evening,

I am working on the first step of livewire. I followed the screencast, but still find converting my current application difficult. I would like to have a dynamic menu. Main menu containing the categories. I have already found the following code and works. Select the menu and the categories as being populated. I thought this was a piece of code provided by Snappy on a website.

Live wire component

<div>
    <div class="mb-8">
        <label class="inline-block w-32 font-bold">Menu:</label>
        <select name="menu" wire:model="menu" class="border shadow p-2 bg-white">
            <option value=''>Choose a Menu</option>
            @foreach($menus as $menu)
            <option value={{ $menu->id }}>{{ $menu->name }}</option>
            @endforeach
        </select>
    </div>

    @if(count($categories) > 0)
    
<div class="mb-8">
        <label class="inline-block w-32 font-bold">Category:</label>
            @foreach($categories as $category)
                <a href="{{route('flows.index', $category->id)}}">{{ $category->name }}</a>
            @endforeach
    </div>
    @endif
</div>

The model:

<?php

namespace App\Http\Livewire;

use App\Models\Category;
use App\Models\Menu;
use Livewire\Component;

class Menus extends Component
{
    public $menu;
    public $categories = [];
    public $category;

    public function render()
    {
        if (!empty($this->menu)) {
            $this->categories = Category::where('menu_id', $this->menu)->get();
        }
        return view('livewire.menus')
            ->withMenus(Menu::orderBy('name')->get());
    }
}

This is working perfectly. But my aim was not using a pulldown, but just regular "links".

So, menu1, menu2, menu3.. And when I click one of these, I would expect to see the categories.

I build these in a sidebar, but no success.

I tried to use the wire:click.prevent option, which parses the data to the model, created a new method for it, but that's it.

                <a wire:click.prevent="category({{ $menu->id }})" href="#">
                    {{ $menu->name }}
                </a>

So im looking for a concept how to proceed and I hope someone can point me out into the right direction.

Kr

Feb
07
2 months ago
Activity icon

Replied to Bootstrap International Dialing Code

Sorry for the late reply, but can you share your controller. the view and model? Did you e.g. updated you model as well? Check the fillable part of the model.

Feb
01
2 months ago
Activity icon

Replied to Bootstrap International Dialing Code

Just do it as a regular input field. Name is something like name=‘int’

In your controller use

public function store(Request $request)
    {
        $name = $request->int;

        //
    }
}

Kr

Jan
30
2 months ago
Activity icon

Replied to Bootstrap International Dialing Code

Maybe you are trying to create a bootstrap input for phonenumbers (with int code?)?

Please check out some samples. If you use BS in your templates, then this is easy to implements. So if so, please share your blade files.

BS example

https://codepen.io/jackocnr/pen/EyPXed

Jan
28
2 months ago
Activity icon

Replied to Delete Functionality Not Working

Thanks and which version of laravel are you using?

Underneath an example which works perfectly fine: You might adjust the one your are using. Laravel 8.x


use App\Http\Controllers\PhotoController;


Route::resource('photos', PhotoController::class);

Activity icon

Replied to Laravel 8 Blade Syntax In Call To Controller

There are some great laravel from scratch serie available. This could give you a knowledge boosts. Even pick the lessons regarding routes..

Activity icon

Replied to Delete Functionality Not Working

Unfortunately you did not share an error message or was is actually not working. So this makes is difficult to answer. But did you create a route for it?

Jan
14
3 months ago
Activity icon

Replied to Can't Acces Database

What kind of sql database are you using and are you using the appropriate drivers for the database?

Activity icon

Replied to Deploy Laravel To Azure [Solved]

Are you able to create the folders manually at all?

Activity icon

Replied to Can I Dive Into Laravel With Basic Php Knowledge

Just start one of the Laravel from scratch lessons. If you can follow them quite easy, you should be good to go.. Btw the are some php lessons as well at laracast.

Jan
12
3 months ago
Activity icon

Replied to Package Creation Help On Tutorial

Do you have the view call Add? And what is the file name of this view?

And maybe you can share some code, how and when the view is being called?

Kr

Dec
08
4 months ago
Activity icon

Replied to Route Not Working Target Class Does Not Exist

I just tried one more time with you solution and it worked.

In the end I used:

Route::get('/viewer', [DemoController::class, 'getViewerPage']);
Route::get('/manager', [DemoController::class, 'getManagerPage']);
Route::get('/user', [DemoController::class, 'getUserPage']);
Route::get('/admin', [DemoController::class, 'getAdminPage']);

Thanks. Now I got the solution, but I would really love to now what is missed :-)

Activity icon

Replied to Route Not Working Target Class Does Not Exist

Hello Siangboon,

Underneath the exact code. I updated it a little, because Im still working on it. But the User and Admin routes does not work, the viewer and manager does work

My routes file


<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/viewer', 'App\Http\Controllers\[email protected]')->name('viewer');
Route::get('/user', 'App\Http\Controllers\[email protected]')->name('user');
Route::get('/manager', 'App\Http\Controllers\[email protected]')->name('manager');
Route::get('/admin', 'App\Http\Controllers\[email protected]')->name('admin');


Route::get('/home', [\App\Http\Controllers\HomeController::class, 'index'])->name('home');

The demo controller:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller
{
    
    public function getViewerPage()
    {
        return view('viewer.index');
    }

    public function getUserPage()
    {
        return view('user.index');
    }

    public function getManagerPage()
    {
        return view('manager.index');
    }

    public function getAdminPage()
    {
        return view('admin.index');
    }


}

As mentioned, nothing fancy, but I just don't see the error. On User and Admin i receive "Target class [DemoController] does not exist."

But in the end I used the solution of GeorgieJackson which turned out to work. But I still don't now what the error was.

Dec
07
4 months ago
Activity icon

Replied to Route Not Working Target Class Does Not Exist

Hello Geordie, I did.. And the DemoContoller works with /admins and not with /admin. So the imput should be okay... What I noticed thought is that in my vendor directory I have multiple folders with the same name and a (2) behind it. I got the impression that something went wrong during the installation.

Thanks for looking into this topic

Dec
06
4 months ago
Activity icon

Replied to Route Not Working Target Class Does Not Exist

Hey I received a error message: Target class [DemoController] does not exist

Activity icon

Replied to Route Not Working Target Class Does Not Exist

Hey GeordieJackson,

Yes I did, and I also did php artisan optimize, but still the same behaviour.

Kr

Activity icon

Started a new Conversation Route Not Working Target Class Does Not Exist

Hello All,

I just have a small question. Laravel is behaving strange (in my opinion :-) ). And I don't now why.

I was struggling for more than a day, just to get a route working. I know Laravel change it logic but still I don't understand.

My question is: Why is /admins and /users working, and if I change these into /admin or /user is give me the "Target class [DemoController] does not exist"

It is just in fresh install of laravel, and these the only routes I have except the default welcome one.

I just want to understand, why the plural is working and the singular not.

Kr esorone

Route::get('/admins', 'App\Http\Controllers\[email protected]');  => WORKS
Route::get('/admin', 'App\Http\Controllers\[email protected]'); => NOT WORKING
Route::get('/users', 'App\Http\Controllers\[email protected]'); => WORKS
Route::get('/user', 'App\Http\Controllers\[email protected]'); => NOT WORKING
Oct
12
6 months ago
Activity icon

Replied to Customer Colours Tailwind Not Working

Hello NYK,

I was in a hurry back then and I made lost of typo's in my initial post. But I meant.. When I run npm.. But deleting cache did the trick.