In Livewire component i have a form inside the modal to edit the information.
When I click on the button, the modal will open and display the item information inside the inputs.
The problem is that if one or all of the inputs do not change their value and the edit button is clicked, it gives the following error that says the values are empty!!. And the inputs must be changed so that there are no errors
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'network' cannot be null (SQL: update `networks` set `network` = ?, `networkName` = ?, `address` = ?, `address_regex` = ?, `tag_memo` = ?, `tag_regex` = ?, `min_withdraw` = ?, `max_withdraw` = ?, `fee` = ?, `deposit` = inactive, `withdraw` = inactive, `networks`.`updated_at` = 2021-06-09 10:18:52 where `id` = 8)
component code:
<?php
namespace App\Http\Livewire\Backend\Currency;
use App\Models\Network;
use Livewire\Component;
class Networks extends Component
{
protected $listeners = ['refreshNetwork' => '$refresh'];
public $confirming;
public $editId;
public $networkEdit;
public $networkNameEdit;
public $address_networkEdit;
public $address_regexEdit;
public $tag_memo_networkEdit;
public $tag_regexEdit;
public $min_withdrawEdit;
public $max_withdrawEdit;
public $feeEdit;
public $depositEdit = false;
public $withdrawEdit = false;
public function editForm($id,$action)
{
if ($network = Network::where('id' , $id)->first()) {
$this->editId = $id;
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
'networkName' => $network->networkName,
'address_network' => $network->address,
'address_regex' => $network->address_regex,
'tag_memo_network' => $network->tag_memo_network,
'tag_memo_regex' => $network->tag_memo_regex,
'min_withdraw' => $network->min_withdraw,
'max_withdraw' => $network->max_withdraw,
'fee' => $network->fee ,
'deposit' => $network->deposit,
'withdraw' => $network->withdraw,
]);
}else{
$this->alert('warning', 'شبکه مورد نظر پیدا نشد !', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function Update($action)
{
if ($action == 'edit')
{
Network::where('id' , $this->editId)->update([
'network' => $this->networkEdit,
'networkName' => $this->networkNameEdit,
'address' => $this->address_networkEdit,
'address_regex' => $this->address_regexEdit,
'tag_memo' => $this->tag_memo_networkEdit,
'tag_regex' => $this->tag_regexEdit,
'min_withdraw' => $this->min_withdrawEdit,
'max_withdraw' => $this->max_withdrawEdit,
'fee' => $this->feeEdit,
'deposit' => $this->depositEdit == false ? 'inactive' : 'active',
'withdraw' => $this->withdrawEdit== false ? 'inactive' : 'active',
]);
$this->emit('refreshNetwork');
$this->dispatchBrowserEvent('hideEditNetworkModal');
$this->alert('success', 'شبکه با موفقیت ویرایش شد.', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function render()
{
return view('livewire.backend.currency.networks');
}
}
modal:
<div wire:key="B" class="modal fade" tabindex="-1" id="editNetworkModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">ویرایـش شبکـه انتقال</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<em class="icon ni ni-cross"></em>
</a>
</div>
<div class="modal-body">
<form action="#" class="form-validate is-alter">
<div class="row gy-3">
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="full-name">شبکه ارز</label>
<div class="form-control-wrap">
<input wire:model.defer="networkEdit" type="text" class="form-control" placeholder="مثال : BNB" id="networkEdit" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="email-address">نام شبکه</label>
<div class="form-control-wrap">
<input wire:model="networkNameEdit" id="networkNameEdit" type="text" class="form-control" placeholder="مثال: BEP20" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">ادرس</label>
<div class="form-control-wrap">
<input wire:model="address_networkEdit" type="text" class="form-control" id="address_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی آدرس شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="address_regexEdit" type="text" class="form-control" id="address_regexEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">آدرس Memo یا Tag</label>
<div class="form-control-wrap">
<input wire:model="tag_memo_networkEdit" type="text" class="form-control" id="tag_memo_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی Memo شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="tag_regexEdit" type="text" class="form-control" id="tag_regexEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداقل برداشت</label>
<div class="form-control-wrap">
<input wire:model="min_withdrawEdit" type="text" class="form-control" id="min_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداکثر برداشت</label>
<div class="form-control-wrap">
<input wire:model="max_withdrawEdit" type="text" class="form-control" id="max_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">کارمزد برداشت</label>
<div class="form-control-wrap">
<input wire:model="feeEdit" type="text" class="form-control" id="feeEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model="depositEdit" type="checkbox" class="custom-control-input" id="depositEdit">
<label class="custom-control-label" for="deposit">واریـز به این آدرس</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model.defer="withdrawEdit" type="checkbox" class="custom-control-input" id="withdrawEdit">
<label class="custom-control-label" for="withdraw">برداشت به این آدرس</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer bg-light">
<button wire:click="Update('edit')" class="btn btn-round btn-outline-primary ">
<div wire:loading wire:target="Update">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-100px">ویرایـش شبکـه</span>
</button>
<button data-dismiss="modal" aria-label="Close" class="btn btn-round btn-outline-secondary w-90px"><span>بستن</span></button>
</div>
</div>
</div>
</div>
and js code to set value for inputs and open modal:
window.addEventListener('editNetworkModal', event => {
$("#editNetworkModal").modal('show');
$('#networkEdit').val(event.detail.network);
$('#networkNameEdit').val(event.detail.networkName);
$('#address_networkEdit').val(event.detail.address_network);
$('#address_regexEdit').val(event.detail.address_regex);
$('#tag_memo_networkEdit').val(event.detail.tag_memo_network);
$('#tag_regexEdit').val(event.detail.tag_regex);
$('#min_withdrawEdit').val(event.detail.min_withdraw);
$('#max_withdrawEdit').val(event.detail.max_withdraw);
$('#feeEdit').val(event.detail.fee);
$('#depositEdit').val(event.detail.deposit);
$('#withdraw').val(event.detail.withdraw);
console.log(event.detail)
});
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
One of the goals of Livewire, is forget about JS for this kind of things. Binding the property with wire:model you don't need at all use JS, even pass this db information through the event. With a simple method that retrieve the data from db and assign it to the public properties is enough for you get this in frontend
public function editForm($id,$action)
{
$this->getModelData($id);
$this->dispatchBrowserEvent('openEditModal');
}
public function getModelData($modelId)
{
$model = Model::find($modelId);
$this->property1 = $model->property1;
//......
}
Related
I have a laravel form to create a new product entry in a database on submit, am supposed to be redirected back but I get a completely blank page without any errors. There is no new entry in my database when I check. The form is made up of various text fields, an image URL, and a multi-selected Image URL
please this is my blade template
<form method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data">
<h4 class="card-title">Create Product</h4><br><br>
#csrf
<div class="row">
<div class="col">
<div class="row mbr-1">
<label for="example-text-input" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input"
class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Price</label>
<div class="col-sm-6">
<input name="catchy_title" class="form-control" type="number"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Status</label>
<div class="col-sm-6">
<input name="status" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Product
Description</label>
<div class="col-sm-8">
<textarea id="elm1" name="long_description" placeholder="Please enter a vivid description of the product"></textarea>
</div>
</div>
<!-- end row -->
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Tags</label>
<div class="col-sm-6">
<input name="tags" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Estimated
Delivery
Time</label>
<div class="col-sm-6">
<input name="estimated_delivery_time" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Available
Quantity</label>
<div class="col-sm-6">
<input name="available_quantity" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Colors</label>
<div class="col-sm-6">
<input name="colors" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Name</label>
<div class="col-sm-6">
<input name="supplier_name" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Contact</label>
<div class="col-sm-6">
<input name="supplier_contact" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Video Url /
Link</label>
<div class="col-sm-6">
<input name="video_description" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Primarry
Image</label>
<div class="col-sm-6">
<input name="primary_image" accept="image/*" class="form-control"
type="file" id="image">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label"> Primary Image
Preview</label>
<div class="col-sm-6">
<img id="showImage" class="" width="300px"
src="{{ !empty($Product->image) ? url('upload/products/' . $product->image) : url('upload/no_image.jpg') }}"
alt="Hero image">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Add Other
Images</label>
<div class="col-sm-6">
<input name="multi_image[]" accept="image/*" class="form-control"
type="file" id="image" multiple="">
</div>
</div>
<!-- end row -->
</div>
</div>
<input type="submit" class="btn btn-info waves-effect waves-light"
value="Create Product">
</form>
and this is my store function
public function store(Request $request)
{
if ($request->file('image')) {
$image = $request->file('image');
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension(); // 3434343443.jpg
Image::make($image)->resize(523,605)->save('upload/home_about/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
$notification = array(
'message' => 'Product created successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Please what am I doing wrong?
thank you for taking some time to review
you are validating the request but not saving it to database.
after the validation and before the return you should do like this to save in database.
$item=new YOUR_MODEL_NAME:
$item->name => $request->name,
$item->category => $request->category,
$item->price => $request->price,
$item->description => $request->description,
$item->status => $request -> status,
$item->tags => $request -> tags,
$item->estimated_delivery_time => $request->estimated_delivery_time,
$item->available_quantity => $request->available_quantity,
$item->colors => $request->colors,
$item->supplier_name => $request->supplier_name,
$item->supplier_phone => $request->supplier_phone,
$item->video_description => $request->video_description,
$item->primary_image => $save_url,
$item->other_images => $save_url,
$item->save();
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
In the snippet above you're performing the validation, but I don't see a request to persist the data to your database in your store() function.
It's recommended to utilize the functionality provided by the framework when checking for request input presence. These functions usually provide quality-of-life aspects such as checking for multiple input presence and conditional callbacks as well.
https://laravel.com/docs/9.x/requests#determining-if-input-is-present
if ($request->has('name')) {
//
}
You should also be calling the validate() method on $request, not $this.
First, I'd like to recommend that you utilize a Form Request
https://laravel.com/docs/9.x/validation#form-request-validation
Second, use the validated data and mass assignment when storing the new model. If the validated data structure is not 1:1 with the table schema, you could always assign the values manually but this will result in a bloated controller. One possible solution is to utilize a DTO (Data Transfer Object) and provide the validated() array to the DTO when using mass assignment.
// Without DTO
Model::create($modelStoreRequest->validated());
// With DTO
$DTO = new MyDTO($modelStore$request->validated())->toArray();
Model::create($DTO);
Note that if the incoming request fields do not pass the given validation rules Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.
Try to be specific, pass route where you want to redirect like below:
return redirect()->route('route-name-here')->with($notification);
i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
here is my code
this is my create blade
<form method="post" action="{{ route('online_classes.store') }}" autocomplete="off">
#csrf
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Grade_id">{{ trans('Students_trans.Grade') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="grade">
<option selected disabled>{{ trans('Parent_trans.Choose') }}...</option>
#foreach ($Grades as $Grade)
<option value="{{ $Grade->id }}">{{ $Grade->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="Classroom_id">{{ trans('Students_trans.classrooms') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="class">
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="section_id">{{ trans('Students_trans.section') }} : </label>
<select class="custom-select mr-sm-2" name="section_id">
</select>
</div>
</div>
</div><br>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>عنوان الحصة : <span class="text-danger">*</span></label>
<input class="form-control" name="topic" type="text">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>تاريخ ووقت الحصة : <span class="text-danger">*</span></label>
<input class="form-control" type="datetime-local" name="start_time">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>مدة الحصة بالدقائق : <span class="text-danger">*</span></label>
<input class="form-control" name="duration" type="text">
</div>
</div>
</div>
<button class="btn btn-success btn-sm nextBtn btn-lg pull-right"
type="submit">{{ trans('Students_trans.submit') }}</button>
</form>
and this is my fillable model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class online_class extends Model
{
protected $fillable = [
'grade_id',
'classroom_id',
'section_id',
'topic',
'start_at',
'duration',
'user_id',
'meeting_id',
'start_url',
'join_url',
'password',
];
public function user(){
return $this->belongsTo(User::class,'user_id');
}
}
and this is my store method in controller
public function store(Request $request)
{
$user = Zoom::user()->first();
$meeting = Zoom::meeting()->make([
'topic' => $request->topic,
'duration' => $request->duration,
'password' => $request->password,
'start_time' => $request->start_time,
'timezone' => 'Africa/Cairo',
]);
$meeting->settings()->make([
'join_before_host' => false,
'approval_type' => 1,
'registration_type' => 2,
'enforce_login' => false,
'waiting_room' => false,
]);
online_class::create([
'grade_id' => $request->grade,
'classroom_id' => $request->class,
'section_id' => $request->section_id,
'topic' => $request->topic,
'start_at' => $request->start_time,
'duration' => $meeting->duration,
'user_id' => Auth::user()->id,
'meeting_id' => $meeting->id,
'start_url' => $meeting->start_url,
'join_url' => $meeting->join_url,
'password' => $meeting->password,
]);
return $user->meetings()->save($meeting);
}
Here is the code for controller:
public function save_product(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'product_category' => 'required',
'description' => 'nullable',
'image1' => 'required',
'image2' => 'nullable',
'image3' => 'nullable',
], [
'product_name.required' => 'Product name field required',
'product_price.required' => 'Asking price field required',
'product_category.required' => 'Product category field required',
'image1.required' => 'You need a upload image-1 field',
]);
if($request->hasFile('image1') || $request->hasFile('image2') || $request->hasFile('image3')){
$file1 = $request->file('image1');
$file2 = $request->file('image2');
$file3 = $request->file('image3');
$text1 = $file1->getClientOriginalExtension();
$text2 = $file2->getClientOriginalExtension();
$text3 = $file3->getClientOriginalExtension();
$fileName1 = time().'.'.$text1;
$fileName2 = time().'.'.$text2;
$fileName3 = time().'.'.$text3;
$file1->move('uploads/product_image', $fileName1);
$file2->move('uploads/product_image', $fileName2);
$file3->move('uploads/product_image', $fileName3);
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
}
return redirect()->route('add_product')
->with('success','Successfully added Product!');
}
Here is the code for blade template:
#extends('admin.layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
#include('pages.partials.flash_message')
</div>
</div>
</div>
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>Add Product</h2>
</div>
<div class="card-body">
<form action="{{route('save_product')}}" method="POST">
#csrf
<div class="form-group">
<label for="exampleFormControlSelect12">Select Category</label>
<input type="text" class="form-control" placeholder="Enter Arrival Time"
id="exampleFormControlSelect12" name="product_category" list="product_category"
autocomplete="off">
<datalist class="form-control" id="product_category" style="display: none" >
<option value="Women Clothes"></option>
<option value="Jewellery"></option>
<option value="Shoes"></option>
<option value="Sun Glass"></option>
<option value="Hair Band"></option>
</datalist>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-1</label>
</div>
#if ($errors->has('image1'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image1') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image1" class="custom-file-input" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-2</label>
<small>*Optional</small>
</div>
#if ($errors->has('image2'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image2') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image2" class="custom-file-input" id="inputGroupFile02"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-3</label>
<small>*Optional</small>
</div>
#if ($errors->has('image3'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image3') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image3" class="custom-file-input" id="inputGroupFile03"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Product Name or Title</label>
<input type="text" name="product_name" class="form-control"
id="exampleFormControlInput1" placeholder="Enter Product Name or Title">
#if ($errors->has('product_name'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_name') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Asking Price</label>
<input type="number" name="product_price" class="form-control"
id="exampleFormControlInput2" placeholder="Enter Asking Price">
#if ($errors->has('product_price'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_price') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product Description</label>
<textarea class="form-control" name="product_description"
id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-footer pt-4 pt-5 mt-4 border-top">
<button type="submit" class="btn btn-primary btn-default">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Route:
Route::post('/admin/add_product','App\Http\Controllers\Admin\AdminController#save_product')
->name('save_product')->middleware('admin');
Model:
protected $fillable = [
'product_name',
'product_category',
'product_price',
'description',
'image1',
'image2',
'image3',
];
Migration:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category');
$table->string('product_price');
$table->text('description')->nullable();
$table->string('image1');
$table->string('image2')->nullable();
$table->string('image3')->nullable();
$table->timestamps();
});
}
I can't find any error in my code please help me to find out. Thanks in advance.
You have to make separate if conditions for each image. Try this:
$fileName1='';
$fileName2='';
$fileName3='';
if($request->hasFile('image1')) {
$file1 = $request->file('image1');
$text1 = $file1->getClientOriginalExtension();
$fileName1 = time() . '.' . $text1;
$file1->move('uploads/product_image', $fileName1);
}
if($request->hasFile('image2')) {
$file2 = $request->file('image2');
$text2 = $file2->getClientOriginalExtension();
$fileName2 = time() . '.' . $text2;
$file2->move('uploads/product_image', $fileName2);
}
if($request->hasFile('image3')) {
$file3 = $request->file('image3');
$text3 = $file3->getClientOriginalExtension();
$fileName3 = time() . '.' . $text3;
$file3->move('uploads/product_image', $fileName3);
}
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
if($product){
return redirect()->route('add_product')->with('success','Successfully added Product!');
}
else{
return redirect()->back()->with('error','Error!');
}
using enctype="multipart/form-data" inside form tag .
When you save, other input data comes to the database, while the data from TourDay does not come. The relationship is established in the Migration and Model section. I could not do it in the controller part, how can I do something..
my blade:
<div class="row">
<div class="col-lg-12">
<div class="card card-custom card-stretch ">
<div class="card-header">
<h3 class="card-title">GRUP OLUŞTUR</h3>
</div>
<form method="post" class="form" id="dynamic_form" enctype="multipart/form-data">
#csrf
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li><b>{{ $error }}</b></li>
#endforeach
</ul>
</div>
#endif
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Otel Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_5" name="hotel[]" multiple="" tabindex="-1" aria-hidden="true">
<optgroup label="Oteller">
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}" >{{$hotel->name}}</option>
#endforeach
</optgroup>
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Grup Kodu :</strong></label>
<div class="col-lg-3">
<div class="input-group input-group">
<div class="input-group-prepend"><span class="input-group-text" >Grup-Kodu:</span></div>
<input type="text" class="form-control form-control-solid" placeholder="TourKey-123-456" name="code" value="{{old('code')}}">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Rehber Ata:</strong></label>
<div class="col-lg-3">
<select class="form-control form-control-solid" id="exampleSelectd" name="guide_id">
#foreach($guides as $guide)
<option value="{{ $guide->id }}" #if(old('guide_id')===$guide->id) selected #endif>{{$guide->full_name}}</option>
#endforeach
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Müşteri Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_3" name="user[]" multiple="" data-select2-id="kt_select2_3" tabindex="-1" aria-hidden="true">
<optgroup label="Müşteriler" >
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->full_name}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Başlangıç Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="started_at" value="{{old('started_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Bitiş Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="finished_at" value="{{old('finished_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label text-lg-right"><strong>Aktivite olacak mı? (Opsiyonel)</strong></label>
<div class="col-lg-3 d-flex justify-content-center">
<div class="radio-inline">
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(0)" #if(old('activity')) checked="checked" #endif name="radios3_1" class="form-control"/>
<span></span>
Evet
</label>
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(1)" #if(!old('activity')) style='display:none' #endif name="radios3_1" class="form-control"/>
<span></span>
Hayır
</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="kt_select2_2"></label>
<div class="col-lg-4">
<div class="form-group" id="myAktivite">
<label for="kt_select2_2"><strong>Aktivite Seçimi Yapın:</strong></label>
<select class="form-control select2 " id="kt_select2_2" name="activity[]" multiple="" data-select2-id="kt_select2_2" tabindex="-1" aria-hidden="true">
<optgroup label="Aktiviteler">
#foreach($activities as $activity)
<option value="{{$activity->id}}">{{$activity->title}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
</div>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="row col-lg-6">
<div class="col-lg-1"></div>
<h4 class="title col-lg-4">TUR EKLE</h4>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Tur Başlığı:</strong></label>
<div class="col-lg-3">
<input type="text" name="tour_title" value="{{old('tour_title')}}" class="form-control form-control-solid" placeholder="Lütfen tur başlığı giriniz"/>
</div>
<label class="col-lg-2 col-form-label text-lg-right"></label>
<div class="col-lg-3">
<div class="custom-file form-group">
<input type="file" class="custom-file-input form-control-solid" id="customFile" multiple>
<label class="custom-file-label" for="customFile">Resim Yükle</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="editable"><strong>İçerik Detay</strong></label>
<div class="col-lg-8">
<textarea id="editable" class="form-control" placeholder="" name="tour_description" value="{{old('tour_description')}}">
</textarea>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-8">
<h3 align="center">Tur Detayı (Gün gün yapılacakları ekleyin):</h3>
<br />
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered table-striped" id="user_table">
<thead>
<tr>
<th width="22%">Başlık(Kaçıncı Gün)</th>
<th width="22%">İçerik</th>
<th width="22%">Öğle Yemeği</th>
<th width="22%">Akşam Yemeği</th>
<th width="12%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div class="card-footer">
<div class="row ">
<div class="col-lg-10 d-flex justify-content-end">
<button type="submit" name="save" id="save" class="btn btn-success mr-2">Kaydet</button>
<button type="reset" class="btn btn-secondary">İptal Et</button>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</form>
</div>
</div>
my script:
<script>
$(document).ready(function(){
var count = 1;
dynamic_field(count);
function dynamic_field(number)
{
html = '<tr>';
html += '<td><input type="text" name="title[]" class="form-control" /></td>';
html += '<td><input type="text" name="description[]" class="form-control" /></td>';
html += '<td><input type="text" name="lunch[]" class="form-control" /></td>';
html += '<td><input type="text" name="dinner[]" class="form-control" /></td>';
if(number > 1)
{
html += '<td><button type="button" name="remove" id="" class="btn btn-light-danger remove"><i class="la la-trash-o">Sil</button></td></tr>';
$('tbody').append(html);
}
else
{
html += '<td><button type="button" name="add" id="add" class="btn btn-light-success"><i class="la la-plus"> Ekle' +
'' +
'</button></td></tr>';
$('tbody').html(html);
}
}
$(document).on('click', '#add', function(){
count++;
dynamic_field(count);
});
$(document).on('click', '.remove', function(){
count--;
$(this).closest("tr").remove();
});
$('#dynamic_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'{{ route("groups.store") }}',
method:'post',
data:$(this).serialize(),
dataType:'json',
beforeSend:function(){
$('#save').attr('disabled','disabled');
},
success:function(data)
{
if(data.error)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<p>'+data.error[count]+'</p>';
}
$('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
}
else
{
dynamic_field(1);
$('#result').html('<div class="alert alert-success">'+data.success+'</div>');
}
$('#save').attr('disabled', false);
}
})
});
});
</script>
my Group Model:
protected $fillable = [
'guide_id','code','started_at','finished_at','tour_title','tour_description'
];
public function tourDays(){
return $this ->hasMany('App\Models\TourDay');
}
my TourDay Model:
protected $fillable = [
'group_id','title', 'description','lunch','dinner'
];
public function group(){
return $this ->belongsTo('App\Models\Group');
}
my GroupController:
public function store(Request $request)
{
$data=$request->only('guide_id','code','started_at','finished_at','tour_title','tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = new TourDay([
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]]);
$group->tourDays()->saveMany($tourDay);
$data = array(
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]
);
$insert_data[] = $data;
}
TourDay::insert($insert_data);
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}
In your store method put this codes:
public function store(Request $request) {
$data=$request->only('guide_id', 'code', 'started_at', 'finished_at','tour_title', 'tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = [
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count],
'group_id' => $group->id
];
TourDay::create($tourDay);
}
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}
I'm attempting to post data to my database using Laravel, but I can't seem to do so. The post route sends to a an expired page.
Here is the route
Route::post('/expenses', 'PropertyExpenseController#store')->middleware('auth');
This is the create and store functions which render the form, and process the form.
public function create($id){
$property = PropertyAdvert::where('id', $id)->first();
return view('/pages/expenses/create', compact('property'));
}
public function store(Request $request){
$PropertyExpenses = PropertyExpenses::create([
"property_id" => $request->property_id,
"user_id" => Auth::user()->id,
"expenseDescription" => $request->description,
"cost" => $request->amount,
"date" => $request->date,
"category" => $request->category
]);
return "Expense Log";
}
This is the view page, where the form is loaded. All the data is got in the controller via the names on the input elements.
<form method="POST" action="/expenses">
<span name="property_id" class="text-muted">{{$property->id}}</span>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label class="" for"description">Expense Description<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<input class="form-control " type="text" name="description">
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"amount">Amount<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4 input-group">
<span class="input-group-addon mr-1 mt-1">€</span>
<input class="form-control" type="text" name="amount">
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"category">Category<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<select class="form-control" id="category" name="category">
<option>Mortgage Payment</option>
<option>Maintainence</option>
<option>Management Fee</option>
</select>
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"description">Date<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<input class="form-control" type="date" name="date">
</div>
</div>
<input type="submit" class="btn btn-primary" value="Log Expense">
</form>
THis is the model, with the fillable array.
class PropertyExpense extends Model
{
protected $fillable = ['property_id'. 'user_id', 'expenseDescription', 'cost', 'date', 'category'];
public function property(){
return $this->belongsTo('App\PropertyAdverts');
}
}
In your form, you need a CSRF Token field.
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Read more here.