Метод App Http LivewireProduct::расширение не существует

#laravel #laravel-livewire

#laravel #laravel-livewire

Вопрос:

Я изучаю laravel livewire, и я впервые использую livewire. У меня возникли проблемы с запуском моего кода на Laravel 8 с помощью laravel-livewire. Когда я нажимаю отправить, всегда отображается подобная ошибка. Я не знаю, что не так и как это исправить

web.php

 <?php
    
use IlluminateSupportFacadesRoute;
use AppHttpLivewireProduct;
Route::get('/products', Product::class);
 

Контроллер

 <?php
    
    namespace AppHttpLivewire;
    
    use LivewireComponent;
    use LivewireWithFileUploads;
    use AppModelsProduct as ProductModel;
    use IlluminateSupportFacadesStorage;
    
    class Product extends Component
    {
        use WithFileUploads;
    
        public $name, $image, $description, $qty, $price;
    
    
        public function previewImage()
        {
            $this->validate([
                'image' => 'image|max:2048'
            ]);
        }
    
        public function store()
        {
            $this->validate([
                'name' => 'required',
                'image' => 'image|max:2048|required',
                'description' => 'required',
                'qty' => 'required',
                'price' => 'required',
            ]);
    
            $imageName = md5($this->image.microtime().'.'. $this->extension());
            
            Storage::putFileAs(
                'public/images',
                $this->image,
                $imageName
            );
    
            ProductModel::create([
                'name' => $this->name,
                'image' => $imageName,
                'description' => $this->description,
                'qty' => $this->qty,
                'price' => $this->price
            ]);
    
            session()->flash('info', 'Product created sSccessfully');
    
            $this->name = '';
            $this->image = '';
            $this->description = '';
            $this->qty = '';
            $this->price = '';
        }
    }
 

В этом мой блейд-код, я надеюсь, что кто-нибудь сможет мне помочь. Спасибо

 <div>
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-body">
                <h2 class="font-weight-bold mb-3">Product List</h2>
                <table class="table table-bordered table-hover table-striped">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Name</th>
                            <th>Image</th>
                            <th>Description</th>
                            <th>Qty</th>
                            <th>Price</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($products as $index=>$product)
                        <tr>
                            <td>{{ $index 1 }}</td>
                            <td>{{ $product->name }}</td>
                            <td>{{ $product->image }}</td>
                            <td>{{ $product->description }}</td>
                            <td>{{ $product->qty }}</td>
                            <td>{{ $product->price }}</td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-body">
                <h2 class="font-weight-bold mb-3">Create Product</h2>
                <form wire:submit.prevent="store">
                    <div class="form-group">
                        <label>Product Name</label>
                        <input wire:model="name" type="text" class="form-control">
                        @error('name') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>

                    <div class="form-group">
                        <label>Product Image</label>
                        <div class="custom-file">
                            <input wire:model="image" type="file" class="custom-file-input" id="customFile">
                            <label for="customFile" class="custom-file-label">Choose Image</label>
                        </div>
                        @error('image') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>
                    @if($image)
                        <label class="mt-2">Image Preview</label>
                        <img src="{{ $image->temporaryUrl() }}" class="img-fluid" alt="Preview Image">
                    @endif

                    <div class="form-group">
                        <label>Description</label>
                        <textarea wire:model="description" class="form-control"></textarea>
                        @error('description') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>

                    <div class="form-group">
                        <label>Qty</label>
                        <input wire:model="qty" type="number" class="form-control">
                        @error('qty') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>

                    <div class="form-group">
                        <label>Price</label>
                        <input wire:model="price" type="number" class="form-control">
                        @error('price') <small class="text-danger">{{ $message }}</small> @enderror
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary btn-block">Submit Product</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card mt-3">
            <div class="card-body">
                <h3>{{ $name }}</h3>
                <h3>{{ $image }}</h3>
                <h3>{{ $description }}</h3>
                <h3>{{ $qty }}</h3>
                <h3>{{ $price }}</h3>
            </div>
        </div>
    </div>
</div>
 

Комментарии:

1. Покажите также свой код представления (блейда).

2. Готово, я обновил сообщение блейд-кодом

3. В store() методе Product компонента, который вы вызываете $this->extension() , но такой метод не определен в этом компоненте, поэтому он не может быть выполнен. Создайте метод, который возвращает желаемое расширение, и ошибка исчезнет.

4. попробуйте $this->image->extension() или File::extension($this->image); вместо $this->extension , extension — это метод класса FIle, в laravel он поставляется с методом file()

5. @KazikM не было необходимости в просмотре?

Ответ №1:

использовать $this->image->extension() или File::extension($this->image);

вместо $this->extension того, чтобы в вашем коде

$imageName = md5($this->image.microtime().'.'. $this->extension());

extension() является ли метод класса FIle, поэтому требуется экземпляр SymfonyComponentHttpFoundationFileUploadedFile класса