Проблема с передачей значений из формы и контроллера в Blade в Laravel

У меня проблема с отправкой значений с адреса localhost / product / 1/1 в мою базу данных, я хочу прикрепить продукт 1 к клиенту 1 и добавить специальные цены ниже Я добавляю код

Маршрут:

Route::get('/product/{customerID}/{productID}', 'CustomerController@insertCustomerProductForm')->name('add-product');
Route::post('/product/{customerID}/{productID}', 'CustomerController@insertCustomerProductAction');
to Controller

insertCustomerProductForm метод:

public function insertCustomerProductForm($customerID, $productID)

{       
       return view('customer_products.create', [
        'customer' => Customer::find('$customerID'),
        'product' => Product::find('$productID'),        ]);    }

insetCustomerProductAction метод:

public function insertCustomerProductAction (Request $request, $customerID, $productID) {        

    $newCustomerProduct = new CustomerProduct;
    $newCustomerProduct->product_id = $productID;
    $newCustomerProduct->customer_id = $customerID;
    $newCustomerProduct->selling_customer_price = $request->input('selling_customer_price'); 
    $newCustomerProduct->purchase_customer_price = $request->input('purchase_customer_price'); 
    $newCustomerProduct->consumed_customer_price = $request->input('consumed_customer_price'); 
    $newCustomerProduct->save();    }

Модель Заказчик Продукт

class CustomerProduct extends Model
{
public function customers()

{
    return $this->belongsToMany(Customer::class);

}

public function products()

{
    return $this->belongsToMany(Product::class);

}}

и когда я пытаюсь использовать значения набора лезвий для продукта клиента, у меня только из значений формы (sales_customer_price ... и т. д.) ничего о продукте и клиенте? Я не знаю, почему или этот метод поиска является проблемой? Потому что я должен хранить в этой форме специальную цену для особых клиентов.

ниже я добавляю часть кода лезвия

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dodaj Produkt') }}  </div>

                <div class="card-body">
                    <form method="post">
                        @csrf

                <div class="form-group row">
                          {{ $customer }}



                   <label for="selling_customer_price " class="col-md-4 col-form-label text-md-right">{{ __('Cena Sprzedaży') }}</label>

                            <div class="col-md-6">
                                <input id="selling_customer_price " type="text" class="form-control{{ $errors->has('selling_customer_price ') ? ' is-invalid' : '' }}" name="selling_customer_price " value="" required autofocus>

                                @if ($errors->has('selling_customer_price '))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('selling_customer_price ') }}</strong>
                                    </span>
                                @endif
                            </div>

моя ошибка выглядит так, будто не видны переменные из формы:

selling_customer_price, purchase_customer_price, consumed_customer_price

У меня ошибка:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'selling_customer_price' cannot be null (SQL: insert into `customer_products` (`product_id`, `customer_id`, `selling_customer_price`, `purchase_customer_price`, `consumed_customer_price`, `updated_at`, `created_at`) values (1, 1, , , , 2018-07-09 12:39:03, 2018-07-09 12:39:03))

person azbroja    schedule 09.07.2018    source источник
comment
Почему вы цитируете переменные? Customer::find('$customerID') '$ customerId'?   -  person Oluwatobi Samuel Omisakin    schedule 09.07.2018


Ответы (1)


В чем именно заключается ваша ошибка в обоих случаях? insertCustomerProductForm должен работать нормально, если вы передаете правильные параметры в URL-адресе, например: localhost/product/20/10

Запрос POST обычно не требует параметров в самом URL-адресе. Вы можете получить переменные POST, выполнив $_POST['selling_customer_price'] в своем insertCustomerProductAction методе.

person Danoctum    schedule 09.07.2018
comment
Я только что отредактировал свой пост и написал свою проблему. Я использовал адрес localhost / product / 20/10, я не могу получить никакой информации о клиенте и продукте, и он не записан в базе данных, я не знаю почему - person azbroja; 09.07.2018
comment
Можете ли вы показать, что вы получаете, когда делаете var_dump($request->input('selling_customer_price')); die(); в своем insertCustomerProductAction методе? - person Danoctum; 09.07.2018
comment
У меня есть /home/vagrant/code/app/Http/Controllers/CustomerController.php:306:null после var_dump - person azbroja; 09.07.2018