I have some columns in my table that are not updating. I have checked everything many times and everything is spelled correctly and should be working.
I have the following in my view:
#section('content')
{{ csrf_field() }}
<h1 class='py-3'>List of Providers</h1>
<div class='form-group'>
<textarea name='survey_providers_list' type='' rows='10' class='form-control' id='' value = '{{ old('survey_providers_list') }}'></textarea>
<div>{{ $errors->first('survey_providers_list') }}</div>
</div>
<h1 class='py-3'>Comments & Questions</h1>
<p>Pleasee let us know any comments or questions you may have about our plan.</p>
<div class='form-group'>
<textarea name='comments' type='' rows='10' class='form-control' id='' value = '{{ old('comments') }}'></textarea>
<div>{{ $errors->first('comments') }}</div>
</div>
<h1 class='py-3'>Individual Health Insurance</h1>
<p>If you do not want to join our plan and would like some assistance evaluating your options in the Individual Health Insurance market, please select 'Yes' below and we will help you with this process.</p>
<div class='form-group'>
<select class='form-control' id='sel1' name='wants_ind_health_quote'>
<option value='Yes' >Yes</option>
<option value='No' >No</option>
</select>
<div>{{ $errors->first('wants_ind_health_quote') }}</div>
</div>
{{-- <h1 class='py-3'>Status</h1>
<div class='form-group'>
<select class='form-control' id='sel1' name='survey_status'>
<option value='In Progress' >In Progress</option>
<option value='Complete' >Complete</option>
</select>
<div>{{ $errors->first('survey_status') }}</div>
</div> --}}
{{-- Submit Button --}}
<div class="container">
<div class="row">
<div class="col text-right">
<button type="submit" name="action" value="next_step" class="btn btn-info">Submit</button>
</div>
</div>
</div>
#endsection
I have the following in my controller:
public function store(Request $request)
{
//
$test = Auth::check();
$userid = Auth::id();
$user = User::find($userid);
if ($test == false){
return redirect('/login');
}
else {
$data = request()->validate ([
'survey_providers_list' => '',
'wants_ind_health_quote' => '',
'comments' => '',
]);
$user->update($data);
return redirect ('/my-employer-plan');
}
}
I have used dd to verify the $user variable is working properly and the $data variable is pulling in the data. Both are working properly. However, the data in my table does not update. All the columns in the table are spelled correctly. All I can think of is that I cannot use the update function here for some reason.
Here is the dd($user):
App\User {#1368 ▼
#guarded: []
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:13 [▼
"id" => 1
"name" => "Wruce Bayne"
"email" => "bobby#test.com"
"email_verified_at" => null
"password" => "$2y$10$cFtf.wT3BE0qbQ68oza8fuKAOYGyTULz1bhzAoL1O3rfHLt3BTI6i"
"active_plan_id" => null
"remember_token" => null
"created_at" => "2020-01-14 22:37:37"
"updated_at" => "2020-01-14 22:37:37"
"survey_providers_list" => null
"wants_ind_health_quote" => null
"comments" => null
"survey_status" => null
]
#original: array:13 [▶]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#rememberTokenName: "remember_token"
}
first in User model add below code
protected $fillable = [
'survey_providers_list' ,
'wants_ind_health_quote' ,
'wants_ind_health_quote'
];
opssss Edit Code : you are filled user model with validation result !!!
$validation = request()->validate ([
'survey_providers_list' => '',
'wants_ind_health_quote' => '',
'comments' => '',
]);
$user->update($request->all());
// Post controller
public function update(Request $request, Post $post)
{
if($post->user_id != Auth::id())
{
Toastr::error('You are not authorized this post!!!!','Error');
return redirect()->back();
}
$this->validate($request,[
'title' =>'required',
// 'zip' => 'zip',
'image' => 'image',
'categories' => 'required',
'tags' => 'required',
'body' => 'required',
'live_demo' =>'required'
]);
$zipfile = $request->file('zip');
$slug = str_slug($request->title);
if (isset($zipfile))
{
$currentDate = Carbon::now()->toDateString();
$zipname = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $zipfile->getClientOriginalExtension();
if (!file_exists('storage/uploads/zip'))
{
mkdir('storage/uploads/zip',0777,true);
}
unlink('storage/uploads/zip/'.$post->zip);
$zipfile->move('storage/uploads/zip',$zipname);
}else{
$zipname = $post->zip;
}
$image = $request->file('image');
$slug = str_slug($request->title);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1600,1066);
if (!file_exists('storage/uploads/post'))
{
mkdir('storage/uploads/post',0777,true);
}
unlink('storage/uploads/post/'.$post->image);
$image_resize->save('storage/uploads/post/'.$imagename);
}else{
$imagename = $post->image;
}
$post->user_id = Auth::id();
$post->title = $request->title;
$post->slug = str_slug($request->title);
$post->image = $imagename;
$post->zip = $zipname;
$post->body = $request->body;
$post->price = $request->price;
$post->live_demo = $request->live_demo;
if(isset($request->status))
{
$post->status =true;
}else
{
$post->status = false;
}
$post->is_approved = false;
$post->save();
$post->categories()->sync($request->categories);
$post->tags()->sync($request->tags);
Toastr::success('Post Successfully Updated:)','Success');
return redirect()->route('user.post.index');
}
}
// Route
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::resource('post','PostController');
});
// Blade file
#extends('layouts.backend.app')
#section('title')
{{__('Post')}}
#endsection
#push('css')
<link href="{{asset('backend/plugins/bootstrap-select/css/bootstrap-select.css')}}" rel="stylesheet" />
#endpush
#section('content')
<div class="container-fluid">
<div class="container-fluid">
<div class="block-header"></div>
<!-- Basic Validation -->
<form action="{{route('user.post.update',$post->id)}}" method="POST" enctype="multipart/form-data">
#csrf
#METHOD('PUT')
<div class="row clearfix">
<div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>{{__('EDIT POST')}}</h2>
</div>
<div class="body">
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('title')}}{{$post->title}}" type="text" class="form-control" name="title" required>
<label class="form-label">{{__('Post Title')}}</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('price')}}{{$post->price}}" type="text" class="form-control" name="price">
<label class="form-label">{{__('Price')}}</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-group">
<img src="{{ asset('storage/uploads/post/'.$post->image) }}" width="40px"height="30px" alt=""/>
<input type="file" class="form-control" name="image" >
<label class="form-label btn btn-primary">{{__(' Your Project ScreenShot')}}</label>
</div>
</div>
<div class="form-group">
<input type="checkbox" id="status" class="filled-in" name="status" value="1" {{ $post->status == true? 'checked' : ''}}>
<label for="status">{{__('Status')}}</label>
</div>
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('live_demo')}} {{$post->live_demo}}" type="text" class="form-control" name="live_demo" required>
<label class="form-label">{{__('Live Demo')}}</label>
</div>
</div>
<div class="form-group">
<input type="file" class="form-control" name="zip" >
<label class="form-label btn btn-warning">{{__(' Your Project Upload')}}</label>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12 col-sm-12 col-xs-12">
<div class="card ">
<div class="header bg-blue">
<h2 class="">{{__('Categrories & Tags')}}</h2>
</div>
<div class="body">
<div class="form-group form-float">
<div class="form-line" {{$errors->has('categories') ? 'fucused error' : '' }}>
<select name="categories[]" id="category" class="form-control show-tick" data-live-search="true" multiple>
<label for="category">{{__('Category Name')}}</label>
#foreach($categories as $category)
<option
#foreach($post->categories as $postCategory)
{{ $postCategory->id == $category->id? 'selected' : '' }}
#endforeach
value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group form-float">
<div class="form-line" {{$errors->has('tags') ? 'fucused error' : '' }}>
<select name="tags[]" id="tag" class="form-control show-tick" data-live-search="true" multiple>
<label for="tag">{{__('Tag Name')}}</label>
#foreach($tags as $tag)
<option
#foreach($post->tags as $postTag)
{{$postTag->id == $tag->id? 'selected' : ''}}
#endforeach
value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
</select>
</div>
</div>
<a class="btn btn-danger" href="{{route('user.post.index')}}">{{__('BACK')}}</a>
<button class="btn btn-primary waves-effect" type="submit">{{__('SUBMIT')}}</button>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>{{__('Documanation')}}</h2>
</div>
<div class="body">
<textarea id="tinymce" name="body">
{{old('body')}} {!! $post->body!!}
</textarea>
</div>
</div>
</div>
</div>
</form>
</div>
#endsection
#push('js')
<script src="{{asset('backend/plugins/bootstrap-select/js/bootstrap-select.js')}}"></script>
<script src="{{ asset('backend/plugins/tinymce/tinymce.js') }}"></script>
<script>
$(function () {
//TinyMCE
tinymce.init({
selector: "textarea#tinymce",
theme: "modern",
height: 300,
plugins: [
'advlist autolink lists link image charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen',
'insertdatetime media nonbreaking save table contextmenu directionality',
'emoticons template paste textcolor colorpicker textpattern imagetools'
],
toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
toolbar2: 'print preview media | forecolor backcolor emoticons',
image_advtab: true
});
tinymce.suffix = ".min";
tinyMCE.baseURL = '{{ asset('backend/plugins/tinymce') }}';
});
</script>
#endpush
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');
});
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 .
Using Laravel-5.8, I am trying to delevop a web application.I have two tables: goals and goal_details. Goal is the main model class.
Using Rules and Request in Laravel:
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required',
'activity' => 'required',
];
}
goals: customer_id, goal_title, weighted_score, start_date, end_date
goal_details: goal_type_id, kpi_description
public function create()
{
$userCompany = Auth::user()->company_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$goaltypes = GoalType::where('company_id', $userCompany)->get();
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities);
}
public function store(StoreGoalRequest $request)
{
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade.php
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI Description<span style="color:red;">*</span></th>
<th scope="col">Attachment</th>
<th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi" ></td>
<td>
<div class="custom-file">
<input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Start Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="start_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> End Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="end_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
javascript
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};
var numRows = $('.activity').length
if (isHod || (!isHod && numRows<3)) {
addRow();
}
});
function addRow() {
var addRow = '<tr>\n' +
' <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
' <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
' <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
' <td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
function addRemoveListener() {
$('.remove').on('click', function () {
var l =$('tbody tr').length;
if(l==1){
alert('you cant delete last one')
}else{
$(this).parent().parent().remove();
}
});
}
</script>
When I submitted, I observed that the fields from goal_details: goal_type_id, kpi_description are not validated as required. It allows null. But all fields in goals are validated.
How do I resolve this?
Thank you.
Check if it can solve your "kpi_description" validation problem :
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'kpi_description' => 'required|array',
'kpi_description.*' => 'required',
'activity' => 'required',
];
}
after defining rules you have to call "validated" method as needed.
try this :
public function store(StoreGoalRequest $request)
{
$validated = $request->validated();
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new GoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->save();
}
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
UserController.php
public function edit_profile(){
$input = Input::all();
$res = array();
$_m = "";
$rules = array(
'userName' => 'required',
'fullName' => 'required',
'shopName' => 'required',
'userType' => 'required',
'email' => 'required',
'aboutMe' =>'required',
'address' =>'required',
'city' =>'required',
'country' =>'required',
'contactNo' =>'required|regex:/[0-9]{10,11}/',
);
$validator = Validator::make($input, $rules);
if (!$validator->fails())
{
$user = User::find(Auth::user()->get()->id);
$user->fullname = $input('fullName');
$user->username = $input('userName');
$user->businessname = $input('shopName');
$user->usertype = $input('userType');
$user->email = $input('email');
$user->aboutme = $input('aboutMe');
$user->address = $input('address');
$user->city = $input('city');
$user->country = $input('country');
$user->phone = $input('contactNo');
$user->save();
$res['success'] = true;
$res['message'] = "NO";
return Redirect::to('user.profile');
}
else
{
return Redirect::to('login');
}
}
profile.blade.php
<div class="tab-pane fade" id="p2">
<h2>Account details</h2>
<div class="hr hr-12 hr-double"></div>
{{ Form::open(array('url'=>'profile','class' =>'form-horizontal')) }}
<div class="form-group">
<label class="col-sm-3 control-label">Full Name:</label>
<div class="col-sm-3">
{{ Form::text('fullName',ucwords(Auth::user()->fullname),array('class'=>'form-control', 'placeholder'=> 'Full Name Here' )) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">User Name:</label>
<div class="col-sm-3">
{{ Form::text('userName',ucwords(Auth::user()->username),array('class'=>'form-control', 'placeholder'=>'e.g ali.ali')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Shop Name:</label>
<div class="col-sm-5">
{{ Form::text('shopName',ucwords(Auth::user()->businessname),array('class'=>'form-control', 'placeholder'=>'e.g Niazi Traders')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Email</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
{{ Form::email('email',ucwords(Auth::user()->email),array('class'=>'form-control', 'placeholder'=>'e.g john.smith#example.com')) }}
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">User Type:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"></span>
{{ Form::select('userType',array('D'=>'Distributor', 'W'=>'Whole Saler','R' =>'Retailer'),ucwords(Auth::user()->usertype)) }}
</div>
</div>
</div>
<hr class="separator">
<div class="form-group">
<label class="col-sm-3 control-label">About Me:</label>
<div class="col-sm-9">
{{ Form::textarea('aboutMe',ucwords(Auth::user()->aboutme),array('class'=>'form-control','id'=>'about-editor','placeholder'=>'Some thing about yourself......')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Address:</label>
<div class="col-sm-7">
{{ Form::text('address',ucwords(Auth::user()->address),array('class'=>'form-control','placeholder'=>'')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">City:</label>
<div class="col-sm-3">
{{ Form::text('city',ucwords(Auth::user()->city),array('class'=>'form-control','placeholder'=>'e.g Islamabad')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Country:</label>
<div class="col-sm-4">
{{ Form::text('country',ucwords(Auth::user()->country),array('class'=>'form-control','placeholder'=>'e.g Pakistan')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phone Number:</label>
<div class="col-sm-3">
{{ Form::text('contactNo',ucwords(Auth::user()->phone),array('class'=>'form-control','placeholder'=>'e.g 0300xxxxxx')) }}
</div>
</div>
<div class="form-actions">
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
{{ Form::submit('Submit',array('class'=>'btn btn-primary')) }}
{{ Form::submit('Cancel',array('class'=>'btn btn-inverse')) }}
</div>
</div>
</div>
{{ Form::close() }}
</div>
Routes.php
Route::get('logout','UserController#get_logout');
Route::get('profile', 'UserController#get_profile');
Route::post('profile', 'UserController#edit_profile');
User.php
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Error lies in this line
$user = User::find(Auth::user()->get()->id);
get is a function of Builder class used for getting a collection of record, Auth::user() returns a single user so you just need to access its id property
change above line to
$user = User::find(Auth::user()->id);
but Auth::user you give the current user so you dont need to find it again, you can access its property directly
$user = Auth::user();