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');
});
Related
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!');
}
Hi all I am new into october cms and I am facing trouble that makes my head spinning around. I have a form that get data from user, I am using builder.
This is my form :
{% put sudah %}{% partial "expert/yes" %}{% endput %}
{% put styles %}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Ubuntu:wght#300;400;500;600;700&display=swap">
{% endput %}
<div class="text-center bg-primary">
<h4 class="text-white my-auto py-5 title-menu">Expert Registration Form</h4>
</div>
<div class="opening" id="first-menu">
<p>Expert Registration Form</p>
<button onclick="changeMenu()" class="btn btn-primary">
Bergabung
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</button>
</div>
<div class="tab-content d-none pb-4" id="second-menu">
<div class=" container">
<div class="head-menu">
<p>Have you registered yet ?</p>
</div>
<div class="p-2">
<div class="form-check my-3">
<input class="form-check-input" type="radio" name="radioPick" id="yes" value="yes" checked>
<label class="form-check-label" for="radioPick">Yes</label>
</div>
<div class="form-check my-3">
<input class="form-check-input" type="radio" name="radioPick" id="no" value="no">
<label class="form-check-label" for="radioPick">No</label>
</div>
</div>
<div class="btn-next mt-4">
<button onclick="secondMenu()" class="btn btn-primary">Next</button>
</div>
</div>
</div>
<div id="yes" class="d-none">
{% placeholder yes%}
</div>
{% put scripts %}
<script>
const changeMenu = () => {
$( "#first-menu" ).addClass('d-none');
$( "#second-menu" ).removeClass('d-none');
}
const secondMenu = () => {
let radio = $('input[name=radioPick]:checked').val()
$( "#second-menu" ).addClass('d-none');
if(radio === 'yes'){
$( "#yes" ).removeClass('d-none');
}
}
</script>
{% endput %}
Then if yes, form for yes appeared
this is yes form :
<form method="POST" action="" accept-charset="UTF-8" enctype="multipart/form-data" id="example" class="something">
<input type="hidden" name="handler" value="onSave">
{{ form_token() }}
{{ form_sessionKey() }}
<div class="tab-content py-4" id="second-menu">
<div class="container">
<div class="content-letter tab">
<p class="title-letter">Please Fill This Form</p>
<div class="content-letter tab">
<div class="mt-3">
<div class="form-group row">
<div class="col-12">
<label class="text-dark font-weight-bold">Nama</label>
<input type="text" class="form-control" placeholder="Name" name="name"
id="name" required>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<label class="text-dark font-weight-bold">Phone</label>
<input type="number" class="form-control" placeholder="Phone" name="phone"
id="phone" required>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<label class="text-dark font-weight-bold">Signature</label>
<div class="row">
<div class="col-9 col-md-10">
<div class="custom-file">
<input type="file" id="signature" class="custom-file input-file"
name="signature" accept="image/x-png,image/gif,image/jpeg">
<label id="label-sign" for="sign"
class="custom-file-label label-files">Upload Signature</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button
id="btn-okay"
type="submit"
data-request="onSave"
data-hotkey="ctrl+s, cmd+s"
data-load-indicator="Creating New..."
class="btn btn-primary">
Join
</button>
</div>
</div>
</form>
and in code section I wrote this function :
function onSave() {
$expert= new Expert();
$model = new \Models\Expert;
$expert->name = Input::get('name');
$expert->phone = Input::get('phone');
$expert->sign= Input::file('signature');
$expert->save();
return Redirect::back;
//or even this one
/*$nama = Input::get('name');
$phone = Input::get('phone');
$sign = Input::file('signature');
DB::table('expert')->insert([
'name' => $name,
'phone' => $phone,
'sign' => $sign
]);
return Redirect::back;*/
}
and not forget I attach model in expert model :
public $attachOne = [
'signature' => 'System\Models\File'
];
Please help me, what is wrong with my code ? Thank you
Check the documents out on working with models. Your php function should be:
use Author\Plugin\Models\Expert;
function onSave() {
$expert= new Expert;
$expert->name = Input::get('name');
$expert->phone = Input::get('phone');
$expert->sign = Input::file('signature');
$expert->save();
return Redirect::back;
}
I am new to laravel and I am working on creating a CMS. I have created a view to create posts but after I input data and click create to submit, page refreshes and shows the same view but with no input and no record created, when it should show a flash message and return the posts index view.
Here is my VIEW HTML:
#section('content')
<div class="card card-default">
<div class="card-header">
{{ isset($post) ? 'Edit Post' : 'Create Post' }}
</div>
<div class="card-body">
<form action="{{ isset($post) ? route('posts.update', $post->id) : route('posts.store') }}" method="POST" enctype="multipart/form-data">
#csrf
#if (isset($post))
#Method('PUT')
#endif
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title" value="{{isset($post) ? $post->title : ""}}">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="5" rows="3" class="form-control">{{isset($post) ? $post->description : ""}}</textarea>
</div>
<div class="form-group">
<label for="content">Content</label>
<input id="content" type="hidden" name="content" value="{{isset($post) ? $post->content : ""}}">
<trix-editor input="content"></trix-editor>
</div>
<div class="form-group">
<label for="published_at">Published at</label>
<input type="text" class="form-control" name="published_at" id="published_at" value="{{isset($post) ? $post->published_at : ""}}">
</div>
#if (isset($post))
<div class="form-group">
<img src="{{ asset('/storage/'.$post->image) }}" alt="" style="width: 100%">
</div>
#endif
<div class="form-group">
<label for="category">Category</label>
<select name="category" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" class="form-control" name="image" id="image">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">
{{ isset($post) ? 'Update Post' : 'Create Post' }}
</button>
</div>
</form>
</div>
</div>
#endsection
Here is METHOD:
public function store(CreatePostRequest $request)
{
$image = $request->image->store('posts');
Post::create([
'title'=>$request->title,
'description'=>$request->description,
'image'=>$image,
'content'=>$request->content,
'published_at' => $request->published_at,
'category_id' => $request->category
]);
session()->flash('success', 'Post Created Successfully');
return redirect(route('posts.index'));
}
What am I doing wrong?
Thanks,
When i try to pass pdf at controller side through ajax at that time file_get_content() gives error like this
file_get_contents(): Filename cannot be empty
My output is like below:-
Illuminate\Http\UploadedFile Object(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 2017-playing-rules.pdf
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => application/octet-stream
[size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 1
[hashName:protected] =>
[pathName:SplFileInfo:private] =>
[fileName:SplFileInfo:private] =>
)
Here "[pathName:SplFileInfo:private]=>" gives null response which should have temp path of my uploaded file.
Here is my ajax call:-
$('#formAddLeague').on('success.form.bv', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url:'{{ url('restoreleague') }}',
data:formData,
type:'post',
dataType:'json',
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$('#loader').hide();
if(data.key == 1)
{
notify('League has been updated Successfully.','blackgloss');
}
}
});
});
In controller i used following:-
$import_rule = $request->file('importRule');
Here is my controller:-
public function restore(Request $request)
{
$league_id = $request->get('hiddenLeagueId');
$import_rule = $request->file('importRule');
$league_rule_url = $request->get('txtLeagueRule');
$objLeague = League::find($league_id);
if (!empty($import_rule)) {
$originalName = $import_rule->getClientOriginalName();
$ruleFileName = pathinfo($originalName, PATHINFO_FILENAME) . '.' . pathinfo($originalName, PATHINFO_EXTENSION);
$s3 = Storage::disk('s3');
$filePath = 'league_rules/' . $ruleFileName;
if ($s3->put($filePath, file_get_contents($import_rule) , 'public'))
{
$ruleURL = $s3->url($filePath);
$objLeague->league_rules = $ruleURL;
$objLeague->rules_filename = $ruleFileName;
}
}
else
if (!empty($league_rule_url))
{
$checkExtension = pathinfo($league_rule_url, PATHINFO_EXTENSION);
if ($checkExtension != 'pdf')
{
$msg = "The selected url extension is not valid.";
return $msg;
}
else
{
$objLeague->league_rules = $league_rule_url;
}
}
$objLeague->league_name = $request->get('txtLeagueName');
$objLeague->league_email = $request->get('txtLeagueEmail');
$objLeague->league_phone = $this->replacePhoneNumber($request->get('leagueContactNo'));
$objLeague->league_info = $request->get('txtLeagueInfo');
$objLeague->level_id = $request->get('txtLevel');
$objLeague->age_required = $request->get('txtMinRequiredAge');
$objLeague->league_website = $request->get('leagueWebsite');
$objLeague->save();
$response['key'] = 1;
return $response;
}
Here is my form:-
<div id="tab2" class="tab-pane">
<form id="formAddLeague" method="post">
{{ csrf_field() }}
<input id="hiddenLeagueId" type="hidden" name="hiddenLeagueId" value="{{$leagueDetail->league_id or ''}}">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label class="control-label"><b>LEAGUE NAME</b></label>
<input type="text" id="txtLeagueName" name="txtLeagueName" value="{{$leagueDetail->league_name or ''}}" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE ID</b></label><br>
<span class="disabled-color" id="leagueId">{{$leagueDetail->league_id or ''}}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>TYPE OF LEAGUE</b></label>
<select id="txtLevel" name="txtLevel" class="form-control">
<option value="">-- Select Type of League --</option>
#foreach($levelList as $level)
<option value="{{ $level->level_id }}" #if($leagueDetail->level_id == $level->level_id) {{"selected='selected'"}} #endif>{{ $level->level_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>MIN AGE REQUIREMENT</b></label>
<select id="txtMinRequiredAge" name="txtMinRequiredAge" class="form-control">
<option value="ALL AGES" #if($leagueDetail->age_required == 'ALL AGES') {{ "selected='selected'" }} #endif>All AGES</option>
<option value="18 AND OVER" #if($leagueDetail->age_required == '18 AND OVER') {{ "selected='selected'" }} #endif>18 AND OVER</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="overflow: visible!important;">
<label class="control-label"><b>SPORTS OFFERED</b></label>
<select id="txtLevel" name="txtLevel" class="form-control selectpicker" multiple data-style="form-control">
#foreach($levelList as $level)
<option value="{{ $level->level_id }}" #if($leagueDetail->level_id == $level->level_id) {{"selected='selected'"}} #endif>{{ $level->level_name }}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE EMAIL</b></label>
<input style="text-transform: lowercase;" type="email" id="txtLeagueEmail" name="txtLeagueEmail" value="{{$leagueDetail->league_email or ''}}" class="form-control" placeholder="Enter Your Email">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE PHONE</b></label>
<input placeholder="(xxx) xxx-xxxx" type="text" name="leagueContactNo" id="leagueContactNo" value="{{$leagueDetail->league_phone or ''}}" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE WEBSITE</b></label>
<input id="leagueWebsite" type="text" name="leagueWebsite" value="{{$leagueDetail->league_website or ''}}" class="form-control" placeholder=" League website">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><b>LEAGUE RULES</b></label>
<div class="row">
<div class="col-md-1">
<div class="radio radio-info">
<input type="radio" name="user_radio" id="file_radio" onclick="leagueRule(1)" checked>
<label> Use File </label>
</div>
</div>
<div class="col-md-11">
<div class="col-sm-12">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput">
<i class="glyphicon glyphicon-file fileinput-exists"></i>
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new"><i class="fa fa-upload"></i></span>
<span class="fileinput-exists">Change</span>
<input type="file" name="importRule" id="importRule">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<div class="radio radio-info">
<input type="radio" name="user_radio" id="url_radio" onclick="leagueRule(2)">
<label> Use URL </label>
</div>
</div>
<div class="col-md-11">
<input disabled type="text" id="txtLeagueRule" name="txtLeagueRule" value="{{$leagueDetail->league_rules or '' }}" class="form-control" placeholder="Enter Link">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<label class="control-label"><b>ABOUT</b></label>
<textarea id="txtLeagueInfo" style="resize: none;" class="form-control" rows="3" data-minwords="3" maxlength="238" name="txtLeagueInfo" placeholder="Type your message">{{$leagueDetail->league_info or ''}}</textarea>
<div id="textarea_feedback" style="text-align:right; color: red"></div>
{{-- <div id="textarea_feedback" class="text-left disabled-color"></div> --}}
</div>
</div>
</div>
<div class="form-group text-left p-t-md">
<button type="submit" class="btn btn-info">UPDATE</button>
</div>
</form>
</div>