Итоговое значение формы ввода SUM с Laravel - PullRequest
1 голос
/ 12 апреля 2019

Я хотел бы создать форму в Laravel (только) с 3 полями: title, price, quantity, имя страницы называется 'create.blade.php'.enter image description here

Моя первая проблема заключается в том, что при вводе 3 значений ничего не происходит!Страница create.blade.php застряла!У меня нет сообщения об ошибке

enter image description here

моя вторая проблема - получить сумму на моей странице 'index.blade.php '

В моей таблице продуктов У меня есть это:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->integer('quantity');
            $table->double('price');
            $table->double('total')->nullable();
            $table->timestamps();
        });
    }

В моем productController У меня есть это:

public function index()
    {
        $products = Product::oldest()->paginate(5);
        return view('admin.products.index', compact('products'))
                  ->with('i', (request()->input('page', 1)-1)*5);
    }


    public function create()
    {

        $products = Product::all();
        return view('admin.products.create', compact('products'));
    }


    public function store(Request $request)
    {
        $request->validate([
                'title' => 'required',
                'quantity' => 'required',
                'price' => 'required',
                'total' => 'required'
        ]);

        Product::create($request->all());

        return redirect()->route('products.index')
                    ->with('success', 'save');
    }

В моем Модельном продукте

 protected  $fillable = ['title', 'quantity', 'price', 'total']; 

    public function setTotalAttribute()
    {
        $this->attributes['total'] = $this->quantity * $this->price;
    }

    public function getTotalAttribute($value)
    {
        return $value;
    }

И в моем create.blade.php У меня есть это:

 <form class="panel-body" action="{{route('products.store')}}" method="POST" novalidate>
              @csrf
              <fieldset class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
                <label for="form-group-input-1">Title</label>
                <input type="text" name="title" id="title" class="form-control" value="{{ old('title')}}"/>
                {!! $errors->first('title', '<span class="help-block">:message</span>') !!}
              </fieldset>

              <fieldset class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
                <label for="form-group-input-1">Quantity</label>
                <input type="text" name="quantity" id="quantity" class="form-control" value="{{ old('quantity')}}"/>
                {!! $errors->first('quantity', '<span class="help-block">:message</span>') !!}
              </fieldset>

              <fieldset class="form-group {{ $errors->has('price') ? 'has-error' : '' }}">
                <label for="form-group-input-1">Price</label>
                <input type="text" name="price" id="price" class="form-control" value="{{ old('price')}}"/>
                {!! $errors->first('price', '<span class="help-block">:message</span>') !!}
              </fieldset>

              <a href="{{route('products.index')}}" class="btn btn-primary pull-right">Back</a>
              <button type="submit" class="btn btn-sm btn-primary">OK</button>

            </form>

Маршрут

Route::resource('/products', 'ProductController');

Файл index.blade.php

@foreach($products as $product)
                <tr>
                   <td> {{$product->title}}</td>
                   <td> {{$product->quantity}}</td>
                   <td> {{$product->price}}</td>
                   <td> {{$product->total}}</td>
                   <td>
                     <form method="POST" action="{{ route('products.destroy', $product) }} ">
                    <a class="btn btn-sm btn-warning" href="{{route('products.edit',$product->id)}}">Editer</a>
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-sm btn-danger">Deleter</button>
                    </form>
                    </td>
                </tr>
                @endforeach

Если я уже знаю, как решить мою первую проблему о создании.blade.php, я счастлив.

Большое спасибо за вашу помощь.

Редактировать: enter image description here

Я не получаю общую сумму ...

1 Ответ

2 голосов
/ 12 апреля 2019

Первая проблема:

В вашем productController вы подтверждаете это 'total' => 'required', но в своем файле create.blade.php вы не отправляете ничего относительно total. В результате проверка возвращает ошибку, но вы ее даже не показываете. Итак, вы думаете, что форма застряла, хотя это не так. На самом деле это перенаправление обратно с ошибкой проверки total требуется.

Вторая проблема

Я не уверен на 100% об этом решении, но вы можете попробовать мутатор ниже. модель.

public function setTotalAttribute()
{
    $this->attributes['total'] = $this->attributes['quantity'] * $this->attributes['price'];
}

Кстати, вам не нужен ненужный метод getTotalAttribute в вашем

Из комментариев

Похоже, вы боретесь с мутатором Eloquent. Итак, давайте удалим метод мутатора setTotalAttribute и метод доступа из модели и в контроллере

заменить следующую строку:

Product::create($request->all());

по следующим строкам:

$data = $request->all(); 
$data['total'] = $request->price * $request->quantity; 
Product::create($data);

Теперь проверьте, работает ли он.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...