Multiple images update Laravel deleted - image

Hi there if anyone can help me, I have the code for updating images and it works fine when I upload another image, and I do not touch the others for example the first image I change and I upload an image the three others I do not touch and I click submit edit button and when I go back to the view of edit I can only see the one photo that I changed the three others are gone..
this is the blade:
<form class="form-horizontal" method="POST"
action="{{ action('website\questions\MatchLinesWithPhotosController#updateQuestion', ['id' => $question->id]) }}"
enctype="multipart/form-data">
{{ csrf_field() }}
#include('website.questions.general-update-header')
<div class="row">
<div class="col-lg-5">
<label style="padding-left: 10px">
<h4 class="box-title">#lang('general.options_for_answers'):</h4>
<em class="text-caption" id="caption-question-type"> *#lang('general.chose_correct_multiple_choice_photo')</em>
</label>
</div>
</div>
<div class="optionsFormMatchlinePhotos">
#for($i=0; $i<=(count($answers->where('deleted', 0))/2)-1; $i++)
<div class="col-md-6" id="option{{ $i }}">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<?php $option = $answers->where('deleted', 0)->where('order', $i)->where('is_key', 1)->first(); ?>
<div class="info-box answer-with-photo-option">
<img src="{{url('/')}}/images/answers/{{ $option->id }}/medium/{{ $option->image_path }}" class="answer-image-create" id="image{{ $i }}">
</div> #if($option)<input onchange="readURL(this, {{ $i }});" type="file" name="image{{ $i }}" id="<?php echo 'answer_file'.$i;?>" style="
margin-top: -19%;
padding-bottom: 9%;
" />
#endif
</div>
</div>
<div class="row">
<div class="form-group {{ $errors->has('options.'.$i) ? ' has-error': '' }}">
<div class="col-md-12">
<div class="col-md-3" style="width: 20%;">
{{-- <input type="text" name="options[{{ $i }}]" value="{{ $i }}" style="display :none" /> --}}
</div>
<input type="text" name="matchanswer[{{ $i }}]" value="{{ $i }}" style="display :none" />
<?php $match = $answers->where('deleted', 0)->where('order', $i)->where('is_key', 0)->first(); ?>
<div class="col-md-5">
#if($match)
<input type="text" name="match{{ $i }}" value="{{$match->text}}"
class="form-control" placeholder="#lang('general.match') {{ $i + 1}}">
#else
<input type="text" name="match{{ $i }}" value=""
class="form-control" placeholder="#lang('general.match') {{ $i + 1}}">
#endif
#if($errors->has('match.'.$i))
<div class="col-md-12"></div>
<span class="help-block">
<strong>{{ $errors->first('match.'.$i) }}</strong>
</span>
#endif
</div>
<div class="col-md-4">
<button type="button" value="{{ $i }}" class="btn btn-flat btn-default btn-sm" id="delete_option" title="#lang('buttons.remove_option')">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
</div>
#endfor
</div>
and here is the edit controller:
public function editQuestionForm($id){
$question = Question::findOrFail($id);
$answers = MatchLineAnswer::where('question_id', $id)->get();
return view('website.questions.partials.matchlineswithphotos.edit-matchlineswithphotos',compact('question', 'answers'));
return session('message');
}
public function updateQuestion(MatchLinesWithPhotosFormRequest $request, $id){
$QuestionController = new QuestionController();
$QuestionController->UpdateQuestion($request, $id);
MatchLineAnswer::where('question_id', $id)->update(['deleted' => 1]);
$to_delete_answers = MatchLineAnswer::select('id')->where('question_id', $id)->get();
MatchLineAnswer::where('question_id', $id)->update(['deleted' => 1]);
$imgController = new ImagesController();
$element = 'answers';
foreach($to_delete_answers as $deleted_answer){
$imgController->deleteImage($element, $deleted_answer->id);
}
foreach ($request['matchanswer'] as $key => $option){
$answer_create = MatchLineAnswer::create([
'question_id' => $id,
'order' => $option,
'is_key' => 1
]);
$img = $request->file('image'. $option);
$create_answer_id = $answer_create->id;
$imgController->uploadAnswerImage($img, $element, $create_answer_id);
$answer_update = MatchLineAnswer::where('id', $create_answer_id)->update(['image_path'=> $imgController->getUniqueNameAttribute()]);
MatchLineAnswer::create([
'question_id' => $id,
'order' => $option,
'text' => strip_tags($request['match'.$option]),
'is_key' => 0
]);
}
$test_id = Question::where('id', $id)->first();
session()->flash('message', 'Question successfully updated');
return redirect()->action('website\tests\CompleteTestController#showAllTestInfo', ['test_id' => $test_id->test_id]);
}

Related

Livewire binding model radio button error

i'm trying to build a polls system using livewire but i got some errors
here is my blade
#foreach ($questions as $index => $question)
<div class="row">
<div class="box-header with-border">
<i class="fa fa-question-circle text-black fs-20 me-10"></i>
<h4 class="box-title">{{ $question->title }}</h4>
</div>
<div class="box-body">
<div class="demo-radio-button">
#foreach ($answers as $key => $answer)
<input wire:model="question{{ $question->id }}" type="radio"
id="answer{{ $question->id }}{{ $key }}"
class="radio-col-primary" value="{{ $key }}">
<label
for="answer{{ $question->id }}{{ $key }}">{{ $answer }}</label>
#endforeach
#error('question')
<div class="text-danger text-bold">{{$message}}</div>
#enderror
</div>
</div>
</div>
#endforeach
my Livewire class
public $question = [];
public function render() {
$category = PollCategory::findOrFail($this->category->id);
$subCategories = PollSubCategory::where('poll_category_id', $category->id)->get();
$answers = PollAnswer::all();
return view('livewire.polls', compact('category', 'subCategories', 'answers'));
}
The Error is
Property [$question41] not found on component: [polls]
Any help please ?
you did it wrong way,
solution:
<input wire:model="question.{{ $question->id }}"
$question{{ $question->id }} equal $question41
$question.{{ $question->id }} equal to $question[41]
that's why u receive error Property [$question41] not found on component

How to Use Select2 Multiple Select in Livewire?

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');
});

Missing required parameter for [Route: BatterFirst.update] [URI: BatterFirst/{BatterFirst}] [Missing parameter: BatterFirst]. edit.blade.php)

While I am doing laravel CRUD project I got . I stuck here its 2 days
Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: BatterFirst.update] [URI: BatterFirst/{BatterFirst}] [Missing parameter: BatterFirst]. (View: C:\xampp\htdocs\CricBangla\resources\views\BatterFirst\edit.blade.php) Error.
I can`t find whire is the error.
Here is my web.php
Route::resource('BatterFirst', BatterFirstController::class);
This is my model BatterFirst.php
class BatterFirst extends Model
{
use HasFactory;
protected $table = 'batterfirst';
protected $fillable = [
'name', 'runs', 'balls', 'sixs', 'fours'
];
}
This is my BatterFirstController.php
<?php
namespace App\Http\Controllers;
use App\Models\BatterFirst;
use Illuminate\Http\Request;
class BatterFirstController extends Controller
{
public function index()
{
$data = BatterFirst::latest()->paginate(5);
return view('BatterFirst.index',compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('BatterFirst.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'runs' => 'required',
'balls' => 'required',
'sixs' => 'required',
'fours' => 'required',
]);
BatterFirst::create($request->all());
return redirect()->route('BatterFirst.index')
->with('success','Batter created successfully.');
}
public function show(BatterFirst $batterFirst)
{
return view('BatterFirst.show',compact('batterFirst'));
}
public function edit(BatterFirst $batterFirst)
{
return view('BatterFirst.edit',compact('batterFirst'));
}
public function update(Request $request, BatterFirst $batterFirst)
{
$request->validate([
'name' => 'required',
'runs' => 'required',
'balls' => 'required',
'sixs' => 'required',
'fours' => 'required',
]);
$batterFirst->update($request->all());
return redirect()->route('BatterFirst.index')
->with('success','Batter updated successfully');
}
public function destroy(BatterFirst $batterFirst)
{
$batterFirst->delete();
return redirect()->route('BatterFirst.index')
->with('success','Batter deleted successfully');
}
}
This is my edit.blade.php
#extends('BatterFirst.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('BatterFirst.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('BatterFirst.update',$batterFirst->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $batterFirst->name }}" class="form-control" placeholder="name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Runs:</strong>
<input type="number" name="runs" value="{{ $batterFirst->runs }}" class="form-control" placeholder="runs"> </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Balls:</strong>
<input type="number" name="balls" value="{{ $batterFirst->balls }}" class="form-control" placeholder="balls"> </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Sixs:</strong>
<input type="number" name="sixs" value="{{ $batterFirst->runs }}" class="form-control" placeholder="sixs"> </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Fours:</strong>
<input type="number" name="fours" value="{{ $batterFirst->fours }}" class="form-control" placeholder="fours"> </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
In this image when i click delete button it showing Batter delete successfully but not deleting Batter
This is my index.blade.php
#extends('BatterFirst.layout')
#section('content')
<div class="row" style="margin-top: 5rem;">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD Example from scratch - laravelcode.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('BatterFirst.create') }}"> Create New Post</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Runs</th>
<th>Balls</th>
<th>Sixs</th>
<th>Fours</th>
<th>Strick Rate</th>
</tr>
#foreach ($data as $key => $value)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->runs }}</td>
<td>{{ $value->balls }}</td>
<td>{{ $value->sixs }}</td>
<td>{{ $value->fours }}</td>
{{-- <td>{{ $value->runs/$value->balls*100 }}</td> --}}
<td>#if ($value->runs > 0 and $value->runs ==0)
{{ $value->runs*100 }}
#elseif ($value->balls>0 and $value->runs ==0)
{{ $value->balls*$value->runs }}
#elseif ($value->balls==0 and $value->runs ==0)
{{ $value->balls * $value->runs }}
#elseif ($value->runs>0 and $value->balls>=0)
{{ $value->runs/$value->balls*100 }}
#endif
</td>
<td>
<form action="{{ route('BatterFirst.destroy',$value->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('BatterFirst.show',$value->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('BatterFirst.edit',$value->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $data->links() !!}
#endsection
Note: I just started learning laravel. Thanks
Try to delete the method POST. Update will use PUT as Method.
<form action="{{ route('BatterFirst.update',$batterFirst->id) }}" method="POST">
#csrf
#method('PUT')
and then change inside your route function this. Pass the id inside a array.
"{{route('BatterFirst.update',['id' => $batterFirst->id])}}"
then will ĺooking so:
<form action="{{ route('BatterFirst.update',['id' => $batterFirst->id]) }}" method="PUT">
#csrf
#method('PUT')
It happens CZ of wrong naming of table and model, folders

Laravel save related data in database

I want to save question_id in answer table using post form
I tried to use foreach or functions but i always got null data
Controller
public function store(Request $request, Survey $survey)
{
$request->validate([
'answer' => 'required',
]);
$survey->option_name = unserialize($survey->option_name);
$answers = new Answer([
'answer' => $request->get('answer'),
'commentaire' => $request->get('commentaire'),
'user_id' => auth()->id(),
'last_ip' => request()->ip(),
'question_id' => $survey->questions,
'survey_id' => $survey->id,
]);
$answers->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
answers table
question table's row :
id
survey_id
title
timestamp
I got always null data or i tried using where but i got errors like id index doesn't exists...
View :
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endempty
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}

Getting validation to work for address in laravel

I'm making a page that before the user submits they need to add their address.
For example: The user goes to the order confirmation and they forget to add their address and they fill in the rest of the page (the page has delivery/collection radio buttons and payment option radio buttons) when the user clicks on the confirm button the page needs to go back and give an error that the address wasn't entered.
The address portion of the page only has a "Add Address" button that takes the user to a form to enter their address.
Is there a way to do this. I thought maybe validation would work but I don't think I'm doing it correctly in this instance.
I have a hidden form that grabs some info and it has an address field in it so that it gets passed into the controller so that I can save it, but it's like it doesn't pick it up
My order-confirmation.blade.php
#extends('layouts.public')
#section('content')
<div class="content_wrapper">
<h1>Order Confirmation</h1>
<?php
$delivery = getDeliveryFee();
?>
{{ $invoice_number }}
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12 mt-15">
#if($message = Session::get('success'))
<div class="alert alert-success" role="alert">
{{ $message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger" role="alert">
{{ $message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Billing Information
</button>
</h2>
</div>
<div id="collapseOne" class="collapse {{ !$errors->any() ? 'show' : '' }}" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<div class="address">
#if ($errors->confirmation_errors->has('delivery_address'))
<div class="help-block text-danger">
<strong>Please add an address NOW</strong>
</div>
#endif
#foreach($addresses as $address)
#if(!empty($address->complex))
{{ $address->complex }},
#endif
<div>{{ $address->address }},</div>
<div>{{ $address->suburb }},</div>
<div>{{ $address->city }},</div>
<div>{{ $address->province }},</div>
<div>{{ $address->postal_code }}</div>
<div class="row edit-delete">
<div class="col-lg-2">
<a class="btn btn-primary edit-button" href="{{ route('account.edit.delivery.address', [$address->id]) }}">Edit</a>
<span>/</span>
</div>
<div class="col-lg-2">
<form action="{{ route('account.delete.delivery.address', [$address->id]) }}" method="post">
#csrf
{{ method_field('DELETE') }}
<button class="btn btn-danger delete-button"><i class="fa fa-pencil"></i> Delete</button>
</form>
</div>
</div>
#endforeach
</div>
</div>
<div class="col-lg-6">
Add Address
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button class="btn btn-link collapsed" id="delivery-collection" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Delivery/Collection
</button>
</h2>
</div>
<div id="collapseTwo" class="collapse {{ $errors->confirmation_errors->any() ? 'show' : '' }}" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p>
Please select your delivery option
</p>
#if ($errors->confirmation_errors->has('delivery_collection'))
<div class="help-block text-danger">
<strong>Please select your delivery option</strong>
</div>
#endif
<div class="delivery-option">
<input type="radio" class="form-check-input {{ $errors->confirmation_errors->has('delivery_collection') ? 'is-invalid' : '' }}" name="delivery-option" id="delivery" value="delivery">
<label for="delivery" class="form-check-label">
Delivery
</label>
<input type="radio" class="form-check-input {{ $errors->confirmation_errors->has('delivery_collection') ? 'is-invalid' : '' }}" name="delivery-option" id="collection" value="collection">
<label for="collection" class="form-check-label">
Collection
</label>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Payment Options
</button>
</h2>
</div>
<div id="collapseThree" class="collapse {{ $errors->any() ? 'show' : '' }}" aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">
#if ($errors->has('payment_option'))
<div class="help-block text-danger">
<strong>Please select a payment option</strong>
</div>
#endif
<div class="row">
<div class="col-lg-12">
<div class="payment-option">
<input type="radio" class="form-check-input {{ $errors->has('payment_method') ? 'is-invalid' : '' }}" name="payment_method" id="payfast-eft" value="payfast-eft">
<label for="payfast-eft" class="form-check-label">
EFT with PayFast
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseThree">
Review Your Order
</button>
</h2>
</div>
<div id="collapseFour" class="collapse" aria-labelledby="collapseFour" data-parent="#accordionExample">
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Code</th>
<th scope="col">Quantity</th>
<th scope="col">Unit Price</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
#foreach($products as $product)
<?php
$image = getImagesArray($product['item']['image']);
?>
<tr>
<th>
#if(!empty($image))
<img src={!! asset("product_images/thumbs/$image[0]") !!}>
#endif
{{ $product['item']['title'] }}
</th>
<td>{{ $product['item']['supplier_code'] }}</td>
<td>{{ $product['qty'] }}</td>
<td>R {{ $product['item']['price'] }}</td>
<td>R {{ $product['price'] }}</td>
</tr>
#endforeach
<tr>
<th colspan="4">
<div class="float-right">
Sub Total
</div>
</th>
<td id="totalPrice" data-price="{{ $totalPrice }}">
R {{ $totalPrice }}
</td>
</tr>
<tr class="delivery-fees">
<th colspan="4">
<div class="float-right">
Delivery Fee
</div>
</th>
<td id="delivery-price" data-price="{{ $delivery }}">
R {{ $delivery }}
</td>
</tr>
<?php
$total = $totalPrice + $delivery;
?>
<tr class="total-price">
<th colspan="4">
<div class="float-right">
Total:
</div>
</th>
<td>
R <span id="completePrice"></span>
</td>
</tr>
</tbody>
</table>
<div class="confirm-order-btn pb-15">
#foreach($products as $product)
<!-- BEGIN PAYFAST EFT -->
<div class="payfast-eft" style="display: none">
<form action="{{ route('payment.gateway') }}" method="POST">
#csrf
<input type="hidden" name="merchant_id" value="merchant_id">
<input type="hidden" name="merchant_key" value="merchant_key">
<input type="hidden" name="return_url" value="{{ route('payfast.success') }}">
<input type="hidden" name="cancel_url" value="{{ route('payfast.cancel') }}">
<input type="hidden" name="m_payment_id" value="{{ $invoice_number }}">
<input type="hidden" name="amount" class="completePrice" value="">
<input type="hidden" name="item_name" value="{{ $product['item']['title'] }}">
<input type="hidden" name="item_description" value="{{ $product['item']['description'] }}">
<input type="hidden" name="email_confirmation" value="1">
<input type="hidden" name="confirmation_address" value="">
<input type="hidden" name="payment_method" value="payfast_eft">
<input type="hidden" name="delivery_collection" class="delivery_collection" value="">
<input type="hidden" name="delivery_fee" class="delivery_fee" value="{{ $delivery }}">
<!-- THIS IS WHERE THE ADDRESS IS ADDED TO THE HIDDEN FORM -->
<input type="hidden" name="delivery_address" class="delivery_address" value="{{ $address }}">
<?php
$success = url('payfast-success');
$cancel = url('payfast-cancel');
$notify = url('payfast-notify');
$original_str = getAscii('merchant_id=merchant_id&merchant_key=merchant_key&return_url='.$success.'&cancel_url='.$cancel.'&notify_url='.$notify.'&m_payment_id=01AB&amount='.$totalPrice.'&item_name=Test Item&item_description=A test product&email_confirmation=1&confirmation_address=email#domain.com&payment_method=eft');
$hash_str = hash('MD5', $original_str);
$hash = strtolower($hash_str);
?>
<input type="hidden" name="signature" value="{{ $hash }}">
<button type="submit" class="btn btn-success float-right confirm-payfast-order">
Confirm Order
</button>
</form>
</div>
<!-- END PAYFAST EFT -->
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var price = $("#totalPrice").data('price'); //get data-price by this syntax
$('#completePrice').html(price);
$('.completePrice').val(price);
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="collection"){
$(".delivery-fees").hide('slow');
var price = $("#totalPrice").data('price'); //get data-price by this syntax
var deliveryprice = 0; //get data-price by this syntax
var totalPrice = parseFloat(price) + parseFloat(deliveryprice);
$('#completePrice').html(totalPrice);
$('.completePrice').val(totalPrice);
$('.delivery_collection').val('collection');
$('.confirm-order').removeAttr('disabled');
$('.confirm-payfast-order').removeAttr('disabled');
}
if($(this).attr("value")=="delivery"){
$(".delivery-fees").show('slow');
var price = $("#totalPrice").data('price'); //get data-price by this syntax
var deliveryprice = $("#delivery-price").data('price'); //get data-price by this syntax
var totalPrice = parseFloat(price) + parseFloat(deliveryprice);
$('#completePrice').html(totalPrice);
$('.completePrice').val(totalPrice);
$('.delivery_collection').val('delivery');
}
});
/* BEGIN EFT PAYFAST */
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="payfast-eft"){
$(".payfast-eft").show('slow');
$(".payfast-card").hide();
$(".i-pay").hide();
$(".confirm-order").hide();
$(".payfast-debit-card").hide();
}
});
/* END EFT PAYFAST */
});
</script>
#stop
my controller function
public function paymentGateway(Request $request)
{
if($request->payment_method == 'payfast_eft')
{
$process = 'Order Paid';
$paid = '1';
}
if($request->delivery_collection == 'collection')
{
$delivery_fee = null;
}else{
$delivery_fee = $request->delivery_fee;
}
$orders = Order::all();
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
$validation = Validator::make($request->all(), $this->getRules());
if($validation->fails())
{
return redirect()->route('cart.deliveryConfirmation')
->withErrors($validation, 'confirmation_errors')
->with('error', 'There were validation errors');
}
foreach($orders as $order)
{
$order = Order::find($order->id)->where('invoice_number', $request->m_payment_id)->first();
$order->cart = serialize($cart);
$order->address = $request->delivery_address;
$order->delivered_date = null;
$order->delivery_fee = $delivery_fee;
$order->delivery_option = $request->delivery_collection;
$order->process = $process;
$order->order_date = Carbon::now('+2:00');
$order->payment_method = $request->payment_method;
$order->paid = $paid;
$order->order_price = $request->amount;
$order->save();
}
$merchant_id = $request->merchant_id;
$merchant_key = $request->merchant_key;
$return_url = $request->return_url;
$cancel_url = $request->cancel_url;
$m_payment_id = $request->m_payment_id;
$amount = $request->amount;
$item_name = $request->item_name;
$item_description = $request->item_description;
$email_confirmation = '1';
$confirmation_address = 'email#domain.com';
$payment_method = $request->payment_method;
$signature = $request->signature;
if($request->payment_method == 'payfast_eft')
{
$url = 'https://sandbox.payfast.co.za/eng/process?merchant_id='.$merchant_id.'&merchant_key='.$merchant_key.'&return_url='.$return_url.'&cancel_url='.$cancel_url.'&m_payment_id='.$m_payment_id.'&amount='.$amount.'&item_name='.$item_name.'&item_description='.$item_description.'&email_confirmation='.$email_confirmation.'&confirmation_address='.$confirmation_address.'&payment_method='.$payment_method;
}
return redirect()->to($url);
}
protected function getRules()
{
return [
'delivery_collection' => 'required',
'payment_method' => 'required',
'delivery_address' => 'required'
];
}
basically on the paymentGateway controller you need to check whether the address is provided if not redirect to the previous page where address is selected and saved in db

Resources