I have tried many times to insert a product which belongs to a category without change in the database
this is controller
class ProduitController extends Controller
{
public function store(Request $request)
{
$pdt=new Produit();
$pdt->nom=$request->input('nomPdt');
$pdt->libelle=$request->input('libelle');
$pdt->qte_stock=$request->input('qte');
$pdt->pu=$request->input('pu');
$pdt->categorie_id=$request->input('categorie');
$pdt->etat=1;
$pdt->save();
}}
View
<form action="{{url('produit/'.$pdt->id)}}" method="post">
<label for="nom">nom:</label><br>
<input type="text" id="" name="nom" value=""><br>
<label for="libelle">libellé:</label><br>
<input type="text" id="" name="libelle" value=""><br>
<label for="qte">Qte en stock:</label><br>
<input type="number" id="" name="qte" value="" min="0"><br>
<label for="pu">PU:</label><br>
<input type="number" id="" name="pu" value="" min="0"><br>
<label for="etat">Etat:</label>
<input type="checkbox" id="" name="etat" ><br>
<label for="selectCategorie">Categorie:</label>
<select id="" name="selectCategorie">
<option value="selectionnez">selectionnez</option>
#foreach ($categories as $cat)
<option value="{{ $cat->id }}"> {{ $cat->nom }} </option>
#endforeach
</select>
for the product table associated with the category table
We aren’t seeing the full picture of the route and uri here. It would be worth verify that. The easiest what to do that would be a temporary dd(‘here’); at the top of your controller's store() method to make sure you are reaching the controller method you expect to. Once that’s verified, you can remove the dd() and move on with confidence.
A few of the input names you reference within the controller do not match those in your form. You need to make sure everything matches the names from the forms.
$pdt=new Produit();
$pdt->nom=$request->input('nom');
$pdt->libelle=$request->input('libelle');
$pdt->qte_stock=$request->input('qte');
$pdt->pu=$request->input('pu');
$pdt->categorie_id=$request->input('selectCategorie');
$pdt->etat=1;//you have this on your form, but have hard coded here?
$pdt->save();
You can also clean this up slightly by loading all the input and using the create() method on the mode.
$inputData = $request()->all();
$pdt = Produit::create([
'nom' => Arr::get($input, 'nom'),
'libelle' => Arr::get($input, 'libelle'),
'qte_stock' => Arr::get($input, 'qte'),
'pu' => Arr::get($input, 'pu'),
'categorie_id' => Arr::get($input, 'selectCategorie'),
'etat’ => 1
]);
Hope this gets things working!
Related
I am working on a Laravel 8 project. I have a row with 3 inputs and a button which can add more line of row. Doesn't matter how many lines I add only the first row is submitted in the database. Please help me with that. Thank you!
index.blade.php:
<h4>Add Products</h4>
<form action="{{ url('insert-products') }}" method="POST" enctype="multipart/form-data">
#csrf
<select class="form-select" name="cateId">
<option value="">Select a Category</option>
#foreach ($category as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
#endforeach
</select>
<br>
<label for="">Product Name</label><br>
<input type="text" name="productName" id="quantity2" required><br>
<br>
<input type="checkbox" name="status" required>
<br>
<div class="customer_records">
<input type="text" name="productName" id="quantity_img2" required>
<input type="text" name="productVariant" required>
<input type="text" name="productValue" required>
<a class="extra-fields-customer" href="#">Add More Customer</a>
</div>
<div class="customer_records_dynamic"></div>
<button type="submit" class="btn btn-outline-success waves-effect" id="type-success">Add Product</button>
</form>
controller:
public function insert(Request $request){
$products = new Products();
$products->cateId = $request->input('cateId');
$products->productName = $request->input('productName');
$products->status = $request->input('status') == TRUE ? '1':'0';
$products->productVariant = $request->input('productVariant');
$products->productValue = $request->input('productValue');
if($products->save()){
return redirect('/categories')->with('status',"Products Added Succesfully");
}
else{
return redirect('/categories')->with('status',"Something went wrong");
}
}
You have several transmissions involved:
The request
First of all, you need to make sure that the values are sent at all. Seeing your code, I presuppose that on the request level a single value is being sent. You will need to indicate that there will be multiple values involved, such as
<label for="">Product Name</label><br>
<input type="text" name="productName[]" id="quantity2" required><br>
<br>
<input type="checkbox" name="status[]" required>
<br>
<div class="customer_records">
<input type="text" name="productName[]" id="quantity_img2" required>
<input type="text" name="productVariant[]" required>
<input type="text" name="productValue[]" required>
<a class="extra-fields-customer" href="#">Add More Customer</a>
</div>
Notice the [] indicating multiplicity.
Sidenote: I would strongly discourage you from hard-coding ids into repeated templates, as they will end up being duplicated, which makes your HTML invalid.
The application
While the previous section should fix an issue, it's not guaranteed that it's the only issue. It makes sense to debug and see what you have on application-side sent by the request. If you have all the values, then all is well and good. If not, then investigate the reason and fix it.
The database
You need to make sure that your code attempts to store everything. If so, then a further question is whether it's done successfully. If not, then you will need to debug your code to see what's wrong.
I am using the validate method to validate user input and when I post a form with errors, I get redirected to the previous page but the form is not repopulated and the errors are not showing. I have include a partial view for showing errors in the page with the form. The partial view is:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
the action method in the controller is:
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'age' => 'required',
'product_code' => 'required|alpha_num',
'price' => 'required|numeric',
]);
$product=new Product();
The view with the form is:
#section('content')
<div class="container">
#include('partials.errors')
<form action="/products/create" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
#csrf
<div class="form-group">
<label>Product Name</label>
<input name="product_name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Age</label>
<input name="age" type="text" class="form-control">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control" name="gender">
<option>
Male
</option>
<option>
Female
</option>
Unisex
</option>
</select>
</div>
<div class="form-group">
<label>Product Code</label>
<input name="product_code" type="text" class="form-control">
</div>
<div class="form-group">
<label>Price</label>
<input name="price" type="text" class="form-control">
</div>
<div class="form-group">
<label>Product Category</label>
<select class="form-control" name="category_name">
#foreach ($product_categories as $product_category)
<option>{{ $product_category->category_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" name="brand_name">
#foreach ($brands as $brand)
<option>{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
</div>
#endsection
when I post a failed form, I get redirected to the view with the form but the form is not repopulated with the input that I entered. additionally, the erros are not shown but just an empty red div. According to a book I read, if the data isn’t valid, the validate method throws a ValidationException and the exception will return a redirect to the previous page, together with all of the user input and the validation errors. I am new to laravel.
You should use old() method to keep repopulate entered value in input field like below
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
To show validation error you have to add errors in each field for example like below
#error("product_code")
<div class="invalid-feedback">{{ $message }}</div>
#enderror
You can read more about old method here
https://laravel.com/docs/8.x/requests#retrieving-old-input
For validation error
https://laravel.com/docs/8.x/validation#the-at-error-directive
First, the CSRF token:
If you check the docs you'll see that you have 2 options how to add it:
#csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
You are doing both, remove one of them.
Second, the old input:
You are missing the old input call. For example:
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
Last, the errors:
You are doing it correctly.
If is still not working, check that your route is using the middleware web.
I have a Laravel application which uses a form to create items. The form uses validation as defined in the Laravel documentation under this section.
I have a StoreItem Request file:
public function rules() {
return [
'item_name'=>'required',
'category_id'=> 'required',
'collection_id'=> 'required',
'brewery_id'=> 'required',
];
}
and in the controller I have the following:
public function store(storeItem $request)
{
$validated = $request->validated();
$item = new Item([
'user_id' => Auth::id(),
'item_name' => $request->item_name,
'category_id' => $request->category_id,
'collection_id' => $request->collection_id,
'brewery_id' => $request->brewery_id,
]);
$item->save();
When validation is catching an error, the create form is presented again but I don't see the old input data.
For the input text fields, I have done the following:
<input type="text" class="form-control" name="item_name" value="{{ old('item_name') }}" />
and this shows the old input data, but what to do for the dropdown boxes like category_id, collection_id and brewery_id. I want them to have the old value as the 'selected' value.
Currently in the form I have (for the dropdown boxes):
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}">{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
This source seems to indicate that using the old() method might even not be needed, but if I don't use the
You need to manually add the selected attribute to the previously selected value. For example:
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ old("brewery_id") == $brewery->id ? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
try this as well. I've added bracket open and close to (old('brewery_id')==$brewery->id)
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ (old('brewery_id') == $brewery->id)? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
All of the other request in my view is included already in the request using
dd($request), but my radio button input is cannot be read by request.
attached here is my code
View
<form method="post" action="{{route('update-dependent')}}">
<div class="form-group">
{{csrf_field()}}
<div class="form-group">
<label>Last Name</label>
<input type="text" name="lname" value="{{$dependent->lname}}" class="form-control">
</div>
<div class="form-group">
{{-- conditional statement to check what geneder --}}
<input type="hidden" name="gender" value="bading" class="form-control">
<label>Male</label>
<input type="radio" name="gender" value="male" class="form-control">
<label>Female</label>
<input type="radio" name="gender" value="female" class="form-control">
</div>
<div class="form-group">
<label>Relationship</label>
<input type="text" name="relationship" value="{{$dependent->relationship}}" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Controller
HMO::UpdateDependent($request);
return redirect()->route('edit', request('hmo_id'));
Model
public static function updateDependent($request)
{
DB::table('hmos_detail')
->where('id', $request->get('dependent_id'))
->update([ 'lname' => $request->get('lname'),
'gender' => $request->get('gender'),
'relationship' => $request->get('relationship'),
return true;
}
result
array:2 [▼
"_token" => "sP9FVEbL3pI5Yaf2jlSfDATNtOTSz2Rheb4bH9Ti"
"lname" => "test"
"relationship" => "WIFE"
]
First of all if you want value of radio then make sure you have proper validation in place.
If you don't know how to validate then have a look at following link
https://laravel.com/docs/5.5/validation#validation-quickstart
Furthermore
If you want some default value for radio button then make sure you have a hidden field that will have default value is this case you dont need validation.
So the basic example would be
<input type="hidden" name="gender" value="bading" class="form-control">
The radio btn will always have bading as default weather its selected or not. But If you add
<input type="radio" name="gender" value="male" class="form-control">
<input type="radio" name="gender" value="female" class="form-control">
Then the hidden field is replaced with the selected value.
As #Sree mentioned, You need to give gender to the fillable.
protected $fillable = ['gender', ....];
As from the documentation :
Mass Assignment You may also use the create method to save a new model
in a single line. The inserted model instance will be returned to you
from the method. However, before doing so, you will need to specify
either a fillable or guarded attribute on the model, as all Eloquent
models protect against mass-assignment by default.
It might be because you forgot to add gender in your Mass Assignment. In your model add,
protected $fillable = ['gender', ....];
I am testing a form. In the form, there are some checkboxes which are with the same name as there are multiple checkboxes to select from.
So my check boxes are like this:
<div class="col-sm-10">
<div class="checkbox">
<input id="department_1" name="departments[]" type="checkbox" value="1">
<label for="department_1">Sales</label>
</div>
<div class="checkbox">
<input id="department_2" name="departments[]" type="checkbox" value="2">
<label for="department_2">Marketing</label>
</div>
<div class="checkbox">
<input id="department_3" name="departments[]" type="checkbox" value="3">
<label for="department_3">Tech Help</label>
</div>
</div>
My testing code is like this:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments')
->press('Submit')
->seePageIs('/users');
}
When I am trying to check if throws error:
InvalidArgumentException: Nothing matched the filter [permissions] CSS
query provided for
If you specify the index for the multiple checkbox in both your form and test, then it works.
Form:
<input id="department_1" name="departments[0]" type="checkbox" value="1">
<input id="department_2" name="departments[1]" type="checkbox" value="2">
Unit test:
public function testUserCreation()
{
$this->be(User::find(10));
$this->visit('/users/create')
->type('First', 'first_name')
->type('Last', 'last_name')
->type('test#esample.com', 'email')
->type('123456', 'password')
->type('123456', 'password_confirmation')
->check('departments[0]')
->press('Submit')
->seePageIs('/users');
}
Using named indexes works as well.
<input name="departments[department_1]" type="checkbox" value="1">
// [...]
$this->check('departments[department_1]');
The only way I managed this was:
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[1]' => '2'
])
->seePageIs('/users');
Note that if you want to check the first and last item, you have to follow the order the inputs are placed.
$this->visit('/users/create')
->submitForm('Submit', [
...
...
'departments[0]' => '1',
'departments[2]' => '3' // index 2 instead 1.
])
->seePageIs('/users');