How to put value of checkvboxes to set json - laravel-5.8

A user cannot bid on a order more than once. If the user clicks on the order again, he should be prompted with a response page noting the user of having previously bid on the order.
I did not do json.
How to save the value checkboxes in json.
My data are saving like:
I create multiple checkboxes and I stored implode computer
order.blade.php
<form action="{{ route('store') }}" method="post">
<input type="checkbox" name="computer[]" value="1" id="hp">
<label for="hp">HP</label>
<input type="checkbox" name="computer[]" value="2" id="dell">
<label for="dell">DELL</label>
<input type="checkbox" name="computer[]" value="3" id="asus">
<label for="asus">ASUS</label>
<input type="checkbox" name="computer[]" value="4" id="acer">
<label for="acer">ACER</label>
<input type="checkbox" name="computer[]" value="5" id="sony">
<label for="sony">Sony</label>
<input type="checkbox" name="computer[]" value="6" id="fujitsu">
<label for="fujitsu">Fujitsu</label>
<input type="checkbox" name="computer[]" value="other_barnds" id="other_barnds">
<label for="other_barnds">Other</label>
</form>
OrderController.php
public function store(Request $request)
{
$this->validate(request(), [
'computer' => 'required'
]);
$order = Order::where('user_id',auth()->id())
->where('computer', request('computer'))
->exists();
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->description = $request->description;
$computer = implode(",", $request->computer);
$order->computer = $computer;
$order->save();
if ($order) {
alert()->error('Warning', 'You ordered already');
return redirect()->back();
}
}

change as below in OrderController.php:
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->description = $request->description;
// json encoding (use array_values if u need values only)
$computer = json_encode($request->computer);
$order->computer = $computer;
$order->save();

Related

How to update table records, but only form fields that have data in them?

In my controller, I have my create record method, but I want to edit existing records, but only update the fields that are filled out. I try to only fill out one or two fields on the edit property file, but no matter what field I fill out, it returns the same error:
Attempt to assign property "property_title" on null
Update method in my controller:
public function update(Request $request, $id)
{
// Find the record
$prop = Property::find($id);
if ($request->hasFile('prop_img')) {
$file = $request->file('prop_img');
$filenameWithExtension = $file->getClientOriginalName();
$Extension = $file->getClientOriginalExtension();
$filenameOnly = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
$filename = $filenameOnly . time() . '.' . $Extension;
$file->move('property_images', $filename);
$prop->property_image = $filename;
}
$prop->property_title = $request->input('prop_title');
$prop->property_description = $request->input('prop_desc');
$prop->bedrooms = $request->input('prop_beds');
$prop->bathrooms = $request->input('prop_baths');
$prop->square_feet = $request->input('prop_ft');
$prop->finished_basement = $request->input('prop_basement');
$prop->prop_tax = $request->input('prop_tax');
$prop->heat_type = $request->input('prop_heat');
$prop->water_heater = $request->input('prop_waterheater');
$prop->year_built = $request->input('prop_year');
$prop->save();
return view('admin.properties');
}
Routes:
Route::group(['prefix' => 'admin'], function() {
Route::get('/', function() {
return view('admin.dashboard');
})->name('admin')->middleware('auth');
Route::get('/properties', [PropertiesController::class, 'index'])->name('all-properties')->middleware('auth');
Route::get('/properties/create', [PropertiesController::class, 'create'])->middleware('auth');
Route::post('/properties/store-property', [PropertiesController::class, 'store'])->name('admin.store_properties')->middleware('auth');
Route::get('/properties/delete/{id}', [PropertiesController::class, 'destroy'])->middleware('auth');
// Edit property
Route::get('/properties/edit/{id}', [PropertiesController::class, 'edit'])->name('admin.edit')->middleware('auth');
Route::post('/properties/update/{id}', [PropertiesController::class, 'update'])->middleware('auth');
});
Edit properties blade file:
#extends( 'layouts.admin' )
#section( 'content' )
<h1 class="admin-header">Edit Listing</h1>
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
#csrf
<div>
<label for="prop_title">Property Title</label>
<input type="text" name="prop_title" id="prop_title" />
</div>
<div>
<label for="prop_desciption">Property Description</label>
<textarea name="prop_desc" id="prop_desc"></textarea>
</div>
<div>
<label for="prop_img">Property Image</label>
<input type="file" name="prop_img" id="prop_img" />
</div>
<div>
<label for="prop_beds">Number of Bedrooms</label>
<input type="number" name="prop_beds" id="prop_beds" steps="1" min="1" />
</div>
<div>
<label for="prop_baths">Number of Bathrooms</label>
<input type="number" name="prop_baths" id="prop_baths" />
</div>
<div>
<label for="prop_ft">Sqaure Feet</label>
<input type="number" name="prop_ft" id="prop_ft" />
</div>
<div>
<label for="props_basement">Finished Basement?</label>
<select name="prop_basement" id="prop_basement">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_tax">Property Tax</label>
<input type="number" name="prop_tax" id="prop_tax" />
</div>
<div>
<label for="props_heat">Heat Type</label>
<select name="prop_heat" id="prop_heat">
<option value="" selected disabled>Select an option</option>
<option value="gas">Gas</option>
<option value="oil">Oil</option>
<option value="electric">Electric</option>
</select>
</div>
<div>
<label for="props_waterheater">Finished Basement?</label>
<select name="prop_waterheater" id="prop_waterheater">
<option value="" selected disabled>Select an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div>
<label for="prop_year">Year Built</label>
<input type="number" name="prop_year" id="prop_year" />
</div>
<button type="submit">Add New Listing</button>
</form>
#endsection
Edit method code:
public function edit($id)
{
return view('admin.edit_property');
}
Results of var_dump
var_dump($id):
string(5) "{$id}"
var_dump($request::all()):
array(8) { ["_token"]=> string(40) "9QOxw20xoy1mEDD6BTWZEJtMpgl3rC16ACejvtcU" ["prop_title"]=> string(4) "Test" ["prop_desc"]=> NULL ["prop_beds"]=> NULL ["prop_baths"]=> NULL ["prop_ft"]=> NULL ["prop_tax"]=> NULL ["prop_year"]=> NULL }
$prop = Property::find($id);
var_dump($prop):
NULL
this error means that this line
$prop = Property::find($id);
returns null, almost because a null value passed to the $id variable
due to the missing $ sign at the action of the edit form, also the variables at the blade should be with double curly braces
So
1- you need to change this line
<form method="POST" action="/admin/properties/update/{id}" class="add_edit_property_form" enctype="multipart/form-data">
to this and it should work with you
<form method="POST" action="/admin/properties/update/{{$id}}" class="add_edit_property_form" enctype="multipart/form-data">
i just added $ sign and in double curly-braces {{$id}}
2- you need to update your edit method, you need to pass the $id parameter to the view
so, you need to update this method
public function edit($id)
{
return view('admin.edit_property');
}
to
public function edit($id)
{
return view('admin.edit_property')->with('id',$id);
}
or to
public function edit($id)
{
return view('admin.edit_property')->with(compact('id'));
}

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?
Route
Route::post('/store/{product}', 'AttachmentController#store')->name('attachment.store');
Product Model
public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
Attachment Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Controller
public function create()
{
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {
$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
Blade View
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
#csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div>
</div>
</form>
You have to use form action like below
<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

how to upload optional documents

I need to upload few files optional. here I add code
<form action="{{ route('UserConfirmation', app()->getLocale()) }}" enctype="multipart/form-data" method="post">
<div class="form-group form-control">{{ csrf_field() }}
<input type="tel" name="ContactNo" value="{{ old('ContactNo') }}" required>
<input class="form-control" type="file" name="nic" required><br>
<input class="form-control" type="file" name="BillingProof" ><br>
<input class="form-control" type="file" name="CashSlip" ><br>
<input class="btn btn-primary" type="submit" name="submit" ><br>
</div>
</form>
here is two required fields, and others are not require,so I need those save in database as empty, here i add my current controller.
public function store(Request $request)
{
//dd($request);
$validator = Validator::make($request->all(), [
'ContactNo' => ['required', 'string','max:15'],
]);
if ($validator->fails()) {
return redirect()->back() ->withErrors($validator)->withInput();
}
$nicPath = $request->file('nic')->store('public');
$billPath = $request->file('BillingProof')->store('public');
$CashSlipPath = $request->file('CashSlip')->store('public');
$UC = $request->all();
$UserCon= new UserConfirm();
$UserCon->ContactNo = $UC['ContactNo'];
$UserCon->NIC = str_replace('public/', '', $nicPath );
$UserCon->BillingProof = str_replace('public/', '', $billPath );
$UserCon->CashSlip = str_replace('public/', '', $CashSlipPath );
$UserCon->Status = "none";
$UserCon->Remark = "none";
$UserCon->save();
Session::flash('UserConfirm','We recived your Documents and we are working on it');
return redirect()->route('feedback',app()->getLocale());
}
and also I add nullable attribute to table fields. here i attach image of table
You should check if the file has been sent at first:
$billPath = $request->hasFile('BillingProof') ? $request->file('BillingProof')->store('public') : null;
$CashSlipPath = $request->hasFile('CashSlip') ? $request->file('CashSlip')->store('public') : null;
and then save it into your storage.

How to order a select the checkboxes product only once in laravel?

A user cannot bid on a order more than once. If the user clicks on the order again, he should be prompted with a response page noting the user of having previously bid on the order.
My data are saving like:
I create multiple checkboxes and I stored implode computer
order.blade.php
<form action="{{ route('store') }}" method="post">
<input type="checkbox" name="computer[]" value="1" id="hp">
<label for="hp">HP</label>
<input type="checkbox" name="computer[]" value="2" id="dell">
<label for="dell">DELL</label>
<input type="checkbox" name="computer[]" value="3" id="asus">
<label for="asus">ASUS</label>
<input type="checkbox" name="computer[]" value="4" id="acer">
<label for="acer">ACER</label>
<input type="checkbox" name="computer[]" value="5" id="sony">
<label for="sony">Sony</label>
<input type="checkbox" name="computer[]" value="6" id="fujitsu">
<label for="fujitsu">Fujitsu</label>
<input type="checkbox" name="computer[]" value="other_barnds" id="other_barnds">
<label for="other_barnds">Other</label>
</form>
OrderController.php
public function store(Request $request)
{
$this->validate(request(), [
'computer' => 'required'
]);
$order = Order::where('user_id',auth()->id())
->where('computer', request('computer'))
->exists();
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->description = $request->description;
$computer = implode(",", $request->computer);
$order->computer = $computer;
$order->save();
if ($order) {
alert()->error('Warning', 'You ordered already');
return redirect()->back();
}
}

Facing Error in updating value in two table in laravel

public function update(Request $request, $user)
{
$user= User::find($user);
$user->name = $request->input('name');
$mobile= Mobile::find($user);
$mobile->id = $request->input('id');
$mobile->country_code = $request->input('country_code');
$mobile->phone_number = $request->input('phone_number');
$user->save();
return redirect('/dashboard')->with('alert-success', 'updated');
}
this code is not working for me ... i want to update the value in two table one table is (user) and second table is (mobile)..
You are not committing the changes to the Mobile model to your database.
Calling $model->save() commits any changes to the that instance of that model object, to the database.
However, it looks like you're using the wrong value to 'find' the mobile model. If you're using Laravel relationships correctly, my edit to that part should help.
I tend to handle changes to my models individually in my code, so it is more readable. Here's how I would do it:
$user= User::find($user);
$user->name = $request->input('name');
$user->save();
$mobile = $user->mobile //this part relies on you having set up the relationship correctly.
$mobile->id = $request->input('id');
$mobile->country_code = $request->input('country_code');
$mobile->phone_number = $request->input('phone_number');
$mobile->save();
Edit A Form
<form class="" action="{{ route('user.update',$user->id) }}" method="POST" name="">
<input type="hidden" name="_method" value="PATCH">
<input type="text" name="id" value="{{$user->id}}">
{{ csrf_field() }}
<Input type="text" name="name" value="{{$user->name}}" >
<Input type="text" name="email" value="{{$user->email}}" >
#if($user->mobile)
<Input type="text" name="country_code" value="{{$user->mobile->country_code}}">
<Input type="text" name="phone_number" value=" {{$user->mobile->phone_number}}">
#else
<Input type="text" name="country_code" value="{{$user->mobile->country_code}}">
<Input type="text" name="phone_number" value=" {{$user->mobile->phone_number}}">
#endif
<button type="submit" class="btn btn-danger btn-sm" value="" >update</span></button>
<span class="pull-right">
</div>
its my edit.blade.php
controller for edit
$editinfo = Mobile::find($user);
return view('edit',compact('user'));
You are not performsave() on $mobile instance
are you forgot add $mobile->save()
you could use tap()function
$user= User::findOrFail($id);
$user_update = tap($user)->update([
'country_code' => $request->input('country_code'),
'phone_number' => $request->input('phone_number'),
]);
further read: https://laravel.com/docs/5.6/helpers#method-tap

Resources