Radio button in my laravel 5.4 cannot be read by request - laravel

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', ....];

Related

Error in passing the foreign key in the form for editing

I have two tables, one named Client and the other named Projects linked together via a foreign key (this is client_id, which is present in Projects).
Each project has an edit button; when I click to edit a project I have a form with all fields secured to it.
To edit a project I have to pass the client id (client_id) associated with that project.
To do this, I did the following:
ROUTE
Route::get('/project/edit/{project}', [ProjectController::class, 'edit'])->name('project.edit');
CONTROLLER
public function edit(Project $project)
{
$client_id = Project::select('client_id')->where('id',$project->id)->get();
//dd($client_id);
return view('project.edit', compact('project','client_id'));
}
VIEW
<div class="row mt-3">
<div class="col-12 col-md-6 namelabel">
<form action="{{route('project.store')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="mb-3">
<input type="hidden" class="form-control" name="client_id" value="{{$client_id}}" >
</div>
<div class="mb-3">
<label for="name" class="form-label">Project name</label>
<input type="text" class="form-control" name="name" value="{{$project->name}}">
</div>
<div class="mb-3">
<div class="mb-3">
<label for="logo" class="form-label">Insert image</label>
<input type="file" name="logo">
</div>
<div class="mb-3">
<label for="project_start_date" class="form-label">Data init</label>
<input type="date" class="form-control" name="project_start_date" value="{{$project->project_start_date}}">
</div>
<label for="description" class="form-label">Description</label>
<textarea name="description" cols="30" rows="10" class="form-control">{{$project->description}}</textarea>
</div>
<button type="submit" class="btn btn-primary mb-5">Modifica progetto</button>
</form>
</div>
</div>
I get the following error:
Incorrect integer value: '[{"client_id":14}]' for column 'client_id' at row 1
How can I solve this problem?
Thanks to those who will help me
This statement
Project::select('client_id')->where('id',$project->id)->get()
does not return the client_id. It returns an Eloquent Collection of Projects with only the client_id Attribute.
You can chain the pluck function to extract only value and then you can call first to get the value from the collection.
Project::select('client_id')
->where('id',$project->id)
->get()
->pluck('client_id')
->first()
After checking your code in the full detail you don't need to do the select part at all.
You have already the Project Model so you can access all of it's fields directly.
$project->client_id
In your view you are doing this already with the name of the project:
{{$project->name}}
You can do the same with the client_id as well:
{{$project->client_id}}

How can i show data from my controller in a textbox?

Hi i calculated a discount in my controller by requesting in a form the percentage and the sale_price, so i did this:
public function store(Request $request){
dd($request->all());
$presupuestoProducto = new PresupuestoProducto();
$presupuestoProducto->sale_price = $request->sale_price;
$presupuestoProducto->discount_percentage = $request->discount_percentage;
$presupuestoProducto->discount = ($sale_price * $discount_percentage)/100;
$presupuestoProducto->save();
Session::flash('success');
return redirect()->route('presupuestos-productos.view');
}
But now i want to make the result of $presupuestoProducto->discount to appear in a textbox. So it would be like an autocomplete field. So up to now i have it this way in my view.
<div class="form-group col-md-2">
<label for="sale_price">Precio de Venta</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Porcentaje de descuento (%)</label>
<input type="number" name="discount_percentage" class="form-control">
</div>
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" class="form-control" value="discount">
</div>
As you can see my last div is an input but i want it to be a text box that automatically appears the result of $presupuestoProducto->discount as i fill in the first two inputs. How should i do this?
you have to use view() and pass the $presupuestoProducto with compact() then you access to the var in your view with it's name
$presupuestoProducto->save();
return view("ProductView",compact( 'presupuestoProducto'))
in view : ProductView
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" placeholder="discount" class="form-control" value={{$presupuestoProducto->discount}} >
</div>
but if you wanna use route you can try route parameter

Laravel - Redirect users back to another form with all data intact, on clicking Previous button

I have two forms as below
Form 1
<form id="form1" action="loc1" method="post">
<div class="form-group">
<label for="exampleDOB">Date of Brth:</label>
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$tuser->DOB ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Next Step</button><br><br>
<button type="button">Previous </button>
</form>
Form 2
<form id="form2" action="loc2" method="post">
<div class="form-group">
<label for="exampleMob">Mobile Number:</label>
<input type="text" class="form-control" id="mobno" name="mobno" placeholder="Valid Mobile
Number" value="{{$tuser->mobno ?? ''}}" >
<div class="error text-danger"></div>
</div>
<button type="submit">Final Step</button><br><br>
<button type="button">Previous </button>
</form>
$tuser is an object containing all the data for that user, from the database
When users click on Next Step in Form 1, the data is stored in database and the user is directed to Form 2.
But the problem is- on clicking the Previous button, I am losing all the pre-filled data in the Previous form. How can I retain form data (to be shown in the input fields as available in the database)?
if you have saved them in DB, so you can retrieve all of it using an id and store it in session like:
session->put("form_1_id",$DBInsertedId);
in form 1 you can check if there are any results, you can retrieve it like:
if(session->has("form_1_id"))
return view('form_1',['filled_data' => Model::find(session->get("form_1_id")) ]);
and in the view you can check for parameter existence form_1_id like you did:
<input type="text" class="form-control" id="dob" name="dob" placeholder="Date of Birth"
value="{{$filled_data->DOB ?? ''}}" >
just add a filled name id in your input view and fill it if form has been filled out before. since doing this can assure you that the filled form will be updated if there was a record for it before:
<input type="hidden" id="id" name="id" value="{{$filled_data->id ?? ''}}" >
and in your controller:
Model::insertOrUpdate(['id' => $request->id ], ... );
UPDATE:
insertOrUpdate Equivalent in psudo-code :
if(DB::exist(['id' => $request->id]))
update(['id' => $request->id , ... ]);
else
insert([ ... ]);

no record inserted in the database in laravel

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!

PhpUnit testing, how to check a checkbox if there are multiple checkboxes with same name in a form

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');

Resources