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 .
Related
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);
}
i use select2 in livewire. When adding data, it worked. But when editing the data, and not changing the data in the select option, the previously selected trainer data is all lost.
Here is the code I made.
Edit.php
<?php
namespace App\Http\Livewire\Admin\Courses;
use App\Models\Course;
use App\Models\Trainer;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithFileUploads;
use \Cviebrock\EloquentSluggable\Services\SlugService;
class Edit extends Component
{
use LivewireAlert;
use WithFileUploads;
public $title, $slug, $cover, $video, $link, $method, $format, $duration, $price, $description, $isActive, $meta_keywords, $meta_description, $addon_styles, $addon_scripts, $courseId;
public $trainer_id;
public function mount($id)
{
$course = Course::findOrFail($id);
if ($course) {
$this->courseId = $course->id;
$this->trainer_id = $course->trainer_id;
$this->title = $course->title;
$this->slug = $course->slug;
$this->link = $course->link;
$this->method = $course->method;
$this->format = $course->format;
$this->duration = $course->duration;
$this->price = $course->price;
$this->description = $course->description;
$this->isActive = $course->isActive;
$this->meta_keywords = $course->meta_keywords;
$this->meta_description = $course->meta_description;
$this->addon_styles = $course->addon_styles;
$this->addon_scripts = $course->addon_scripts;
}
}
public function updatedTitle()
{
$this->slug = SlugService::createSlug(Course::class, 'slug', $this->title);
}
public function update()
{
$course = Course::where('id',$this->courseId)->first();
$this->validate([
'title' => 'required',
'cover' => $this->cover ? 'required|image|mimes:png,jpg,webp,jpeg' : '',
'description' => 'required',
]);
if ($this->cover) {
\Storage::delete('public/'.$course->cover);
$fileName = time().'_'.$this->cover->getClientOriginalName();
$filePath = $this->cover->storeAs('images/courses', $fileName, 'public');
} else {
$filePath = $course->cover ?? null;
}
if ($this->video) {
\Storage::delete('public/'.$course->video);
$fileName = time().'_'.$this->video->getClientOriginalName();
$video = $this->cover->storeAs('images/courses', $fileName, 'public');
} else {
$video = $course->video ?? null;
}
$course->update([
'title' => $this->title,
'slug' => $this->slug,
'cover' => $filePath,
'video' => $this->video ? $video : null,
'link' => $this->link,
'method' => $this->method,
'format' => $this->format,
'duration' => $this->duration,
'price' => $this->price,
'description' => $this->description,
'isActive' => $this->isActive,
'meta_keywords' => $this->meta_keywords,
'meta_description' => $this->meta_description,
'addon_styles' => $this->addon_styles,
'addon_scripts' => $this->addon_scripts
]);
$course->trainers()->sync($this->trainer_id);
$this->alert('success', 'Data updated successfully.');
return redirect()->route('courses.index');
}
public function render()
{
return view('livewire.admin.courses.edit',[
'trainers' => Trainer::where('isActive',true)->get(),
'course' => Course::find($this->courseId)
])
->extends('layouts.app')
->section('content');
}
}
edit.blade.php
<div>
#section('title', 'Edit Course')
#section('styles')
<script src="{{ asset('vendor/tinymce/tinymce.min.js') }}"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
span .selection {
display: block;
}
</style>
#endsection
<!-- ========== title-wrapper start ========== -->
<div class="title-wrapper pt-30">
<div class="row align-items-center">
<div class="col-md-6">
<div class="title mb-30">
<h2>Edit Course</h2>
</div>
</div>
<!-- end col -->
<div class="col-md-6">
<div class="breadcrumb-wrapper mb-30">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
Dashboard
</li>
<li class="breadcrumb-item">
Courses
</li>
<li class="breadcrumb-item active" aria-current="page">
Edit Course
</li>
</ol>
</nav>
</div>
</div>
<!-- end col -->
</div>
<!-- end row -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="card-style mb-3">
<form wire:submit.prevent="update" class="row g-3">
<input type="hidden" wire:model="courseId">
<div class="col-12">
<div class="mb-3">
<label for="cover" class="form-label">Cover</label><br>
#if ($cover)
Cover Preview:
<div class="card mb-3">
<img src="{{ $cover->temporaryUrl() }}" class="w-15 rounded-3">
</div>
#else
<div class="card mb-3">
<img src="{{ asset('storage/'.$course->cover) }}" class="w-15 rounded-3 img-fluid">
</div>
#endif
<input type="file" wire:model="cover" class="form-control #error('cover') is-invalid #enderror" id="cover">
#error('cover')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input type="text" wire:model="title" class="form-control #error('title') is-invalid #enderror" id="title" placeholder="Course Title">
#error('title')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="slug" class="form-label">Slug</label>
<input type="text" wire:model="slug" class="form-control #error('slug') is-invalid #enderror" id="slug" placeholder="course-slug">
#error('slug')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3" wire:ignore>
<label for="description" class="form-label">Description</label>
<textarea wire:model="description" class="form-control #error('description') is-invalid #enderror" id="description" rows="15"></textarea>
#error('description')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="video" class="form-label">Video</label>
<input type="file" wire:model="video" class="form-control" id="video">
</div>
<div class="mb-3">
<label for="link" class="form-label">Link</label>
<input type="url" wire:model="link" class="form-control" id="link" placeholder="Youtube link">
</div>
<div class="mb-3">
<label for="method" class="form-label">Method</label>
<input type="text" wire:model="method" class="form-control" id="method" placeholder="Example: online, hybrid">
</div>
<div class="mb-3">
<label for="format" class="form-label">Format</label>
<input type="text" wire:model="format" class="form-control" id="format" placeholder="Eg: HD Video, Live Concultation">
</div>
<div class="mb-3">
<label for="duration" class="form-label">Duration</label>
<input type="text" wire:model="duration" class="form-control" id="duration" placeholder="Eg: 3 mounts">
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" wire:model="price" class="form-control #error('price') is-invalid #enderror" id="price" placeholder="Eg: 250000">
#error('price')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3" wire:ignore>
<label for="trainer" class="form-label">Trainer</label>
<select multiple="multiple" id="trainer" class="form-select #error('trainer_id') is-invalid #enderror" multiple>
#foreach ($trainers as $trainer)
<option {{ $course->trainers()->find($trainer->id) ? 'selected' : '' }} value="{{ $trainer->id }}">{{ $trainer->name }}</option>
#endforeach
</select>
#error('trainer_id')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-12">
<div class="mb-3">
<label for="meta_keywords" class="form-label">Meta Keywords</label>
<input type="text" wire:model="meta_keywords" class="form-control" id="meta_keywords" placeholder="keyword1, keyword2, keyword3">
</div>
</div>
<div class="col-12">
<div class="mb-3">
<label for="meta_description" class="form-label">Meta Description</label>
<input type="text" wire:model="meta_description" class="form-control" id="meta_description" placeholder="Meta description">
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck" wire:model="isActive">
<label class="form-check-label" for="gridCheck">
Set active
</label>
</div>
</div>
<button type="submit" class="w-100 main-btn primary-btn btn-hover btn-sm" wire:target="update" wire:loading.class="deactive-btn">
<span wire:loading.remove wire:target="update">
Update
</span>
<span wire:loading wire:target="update" class="text-center">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading...
</span>
</button>
</form>
</div>
</div>
</div>
</div>
#push('scripts')
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
<x-livewire-alert::scripts />
<script>
tinymce.init({
selector: 'textarea',
menubar: 'file edit view insert format tools table help',
plugins: [
"advlist autolink autosave codesample lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table toc directionality",
"emoticons template paste textpattern"
],
toolbar: "restoredraft insertfile undo redo | styleselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify codesample | bullist numlist outdent indent toc| link image media",
setup: function(editor) {
editor.on('change', function(e) {
console.log('the content ', editor.getContent());
#this.set('description', editor.getContent());
});
}
});
</script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$('#trainer').select2();
$('#trainer').on('change', function (e) {
var data = $('#trainer').select2("val");
#this.set('trainer_id', data);
});
});
</script>
#endpush
How to solve this problem? so that, when I edit the data and without changing the data in select2, the data will not be deleted.
Thank you
This worked for me.
when editing my modal i load my data to my array as follows;
public $selectedOn = [];
public function edit($id){
$foos = Foo::where('other_id',$id)->get();
foreach($foos as $foo){
array_push($this->selectedOn, $foo->id);
}
$this->emit('selectLoadOk');
}
in my js I do the following;
window.livewire.on('selectLoadOk', () =>{
$('#selectChecklist').trigger('change');
});
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;
//......
}
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!');
}
<form id="add-record" enctype="multipart/form-data">
#csrf
<div class="success">
</div>
<div class="form-group row">
<label for="name" class="col-sm-3 label-name col-form-label">Full Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control input" id="name" name="name" placeholder="Full Name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="name-error"></span>
</div>
</div>
<div class="form-group row">
<label for="datepicker" class="col-sm-3 col-form-label">Date of birth</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-calendar"></i></span>
</div>
<input type="text" class="form-control input" id="datepicker" name="dateofbirth" placeholder="">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="dateofbirth-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Gender</label>
<div class="col-sm-9 input-group">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="male" value="Male" checked>
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="female" value="Female">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="address" class="col-sm-3 col-form-label">Address</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-home"></i></span>
</div>
<input type="text" class="form-control input" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="address-error"></span>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-3 col-form-label">Email</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
</div>
<input type="email" class="form-control input" id="email" name="email" placeholder="yourmail#email.com">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="email-error"></span>
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-sm-3 col-form-label">Phone Number</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="text" class="form-control input" id="phone" name="phone" placeholder="+3784773847">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="phone-error"></span>
</div>
</div>
<div class="form-group row">
<label for="course" class="col-sm-3 col-form-label">Course Name</label>
<div class="col-sm-9 input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-book-open"></i></span>
</div>
<input type="text" class="form-control input" id="course" name="course" placeholder="Course name">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="course-error"></span>
</div>
</div>
<div class="form-group row">
<label for="image-file" class="col-sm-3 col-form-label">Your Image</label>
<div class="col-sm-9 input-group">
<input type="file" class="form-control-file input-image" name="image" id="image-file">
</div>
</div>
<div class="row error">
<div class="col-sm-9 offset-sm-3">
<span class="text-danger" id="image-error"></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3 input-group">
<input type="submit" class="btn btn-primary">
</div>
</div>
</form>
strong text
When i dd($request->all()); in store function in controller, i get all other values but not image.. It even doesn't shows image=null when i dd(); array:8 [ "_token" => "C27oLkk8wDTcBnZDA38nPCte4SY18HqXqxcFDcrI" "name" => null "dateofbirth" => null "gender" => "Male" "address" => null "email" => null "phone" => null "course" => null ]
Iam using ajax request Although i input the image it shows the image is required.. What am i doing wrong here??
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
$name = $request['name'];
$dateofbirth = $request['dateofbirth'];
$gender = $request['gender'];
$address = $request['address'];
$email = $request['email'];
$phone = $request['phone'];
$course = $request['course'];
if($request->hasFile('image')) {
$img_name = time() . '.' .$request->file('image')->getClientOriginalExtension();
$destinationPath = public_path('/assets/images/');
$request->file('image')->move($destinationPath, $img_name);
$image = $img_name;
}
Student::create([
'name' => $name,
'dateofbirth' => $dateofbirth,
'gender' => $gender,
'address' => $address,
'email' => $email,
'phone' => $phone,
'course' => $course,
'image' => $image,
]);
You can try this
$validator = Validator::make($request, [
'name' => 'required|min:2',
'dateofbirth' => 'required|date',
'gender' => 'required',
'address' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'course' => 'required',
'image' => 'required|file|mimetypes:image/jpeg,image/png',
]);
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]);
}
//store image
$path = $request->image->store('images');
//it will store your images at `storage/app/public/images` folder with dynamically generated image name, be sure create images folder there
Student::create([
'name' => $request->name,
'dateofbirth' => $request->dateofbirth,
'gender' => $request->gender,
'address' => $request->address,
'email' => $request->email,
'phone' => $request->phone,
'course' => $request->course,
'image' => $path,
]);
Execute this command from command line
php artisan storage:link
it will create symbolic link of storage/app/public to public/storage folder.
now you can use your image in view like this
{{asset('storage/images/test.jpeg')}}
If you have to read that file in controller then you can use it like this
Storage::disk('public')->get('images/test.jpeg');
Always store your files in storage folder. All public files should be stored at storage/app/public
For details check here https://laravel.com/docs/5.6/filesystem#introduction