It has been resolved, here is the updated code
View
@include('Admin.Includes.header')
@php
use Illuminate\Support\Facades\Auth;
$logged_in_user = Auth::user();
@endphp
<!-- Page Inner Start -->
<!--================================-->
<div class="page-inner">
<!--================================-->
<!-- Breadcrumb Start -->
<!--================================-->
<div class="pageheader pd-t-25 pd-b-35">
<div class="d-flex justify-content-between">
<div class="clearfix">
<div class="pd-t-5 pd-b-5">
<h1 class="pd-0 mg-0 tx-20 tx-dark">{{ __('Create Project') }}</h1>
</div>
<div class="breadcrumb pd-0 mg-0">
<a class="breadcrumb-item" href="{{url('/')}}/admin"><i class="icon ion-ios-home-outline"></i> Dashboard</a>
<a class="breadcrumb-item" href="{{url('/')}}/admin/projects">Projects</a>
<span class="breadcrumb-item active">Create</span>
</div>
</div>
<div class="d-flex align-items-center">
<button type="button" onclick="window.location = '{{url('/')}}/admin/projects'" class="btn btn-default mb-2 mb-md-0 d-none d-lg-block pd-t-6-force pd-b-5-force">
<i data-feather="package" class="wd-16 mr-2"></i>Projects List</button>
<button type="button" onclick="window.location = '{{url('/')}}/admin/projects/list/trash'" class="btn btn-default mb-2 mb-md-0 d-none d-lg-block pd-t-6-force pd-b-5-force">
<i data-feather="package" class="wd-16 mr-2"></i>Trash List</button>
</div>
</div>
</div>
<!--/ Breadcrumb End -->
<!--================================-->
<!--================================-->
<div class="col-md-12 col-lg-12 px-0">
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
<li>If you have already selected featured image, and variation thumbnail images, Please select them again!</li>
</ul>
</div>
@endif
<form id="project-create-form" method="POST" action="{{ route('projects.store') }}" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-md-9">
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Project Details (Compulsory)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">Title: <span class="tx-danger">*</span></label>
<input class="form-control form-control-lg restrict-input-alphabets_space addTitle" type="text" name="project_title" placeholder="Palestine Emergency Appeal..." value="{{ old('project_title') }}" required>
</div>
<div class="form-group">
<label class="form-control-label active">Permalink: <span class="tx-danger">*</span></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text input-group-text">{{url('/')}}/projects/</span>
</div>
<input class="form-control form-control restrict-input-alphabets permalink" id="permalink" type="text" name="permalink" value="{{ old('permalink') }}" placeholder="palestine-emergency-appeal" required>
</div>
<div class="text-danger permalink_error"></div>
<input type="hidden" class="permalink_status" name="permalink_status" value="{{ old('permalink_status') }}" required>
</div>
</div>
</div>
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Project Details (Optional)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">Short Description: </label>
<textarea class="form-control" id="short_description" name="short_description" placeholder="Short Description...">{{ old('short_description') }}</textarea>
</div>
<div class="form-group">
<label class="form-control-label active">Long Description: </label>
<textarea class="form-control" id="long_description" name="long_description" placeholder="Long Description..."> {{ old('long_description') }}</textarea>
</div>
</div>
</div>
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Project Donation Variation') }}</h6>
</div>
<button type="button" class="btn badge text-light bg-primary add_variation_contatiner">Add Variation</button>
</div>
</div>
<div class="card-body variations_backlog">
@if ($errors->any())
@php $variations = DB::table('project_temp_variation')->where('user_id', $logged_in_user->id)->get(); @endphp
@if(sizeof($variations) > 0)
@php $i = 1; @endphp
@foreach($variations as $variation)
<div class="border border-secondary rounded p-1 project_variation_container mb-3">
<div class="variation_img_box">
<button type="button" class="change-img-btn btn badge bg-primary">Change</button>
<img class="variation_img" src="/Placeholder.png">
<input type="file" accept="image/*" class="variation_img" name="variation_img_{{$i}}" value="" style="display:none;">
<button type="button" class="remove-img-btn btn badge bg-warning"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
<div class="variations_inputs px-1 w-100">
<div class="input-group title_price_group">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Variation Title</span>
</div>
<input type="hidden" name="variations_count[]" value="variation">
<input type="text" class="form-control rounded-0 variation_title" name="variation_title_{{$i}}" value="{{$variation->title}}" placeholder="Variation Title">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Price</span>
</div>
<input type="number" class="form-control rounded-0 variation_price" name="variation_price_{{$i}}" value="{{$variation->price}}" placeholder="Price" value="0" min="0" step="0.01">
</div>
<div class="input-group description_group mt-2">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Description</span>
</div>
<input type="text" class="form-control rounded-0 variation_description" name="variation_description_{{$i}}" value="{{$variation->description}}" placeholder="Description...">
</div>
<button type="button" class="remove_variation btn btn-sm btn-danger p-1"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
</div>
@php $i++; @endphp
@endforeach
@endif
@else
<div class="alert alert-warning border-dark empty_variation_field">Click to <b>Add Variation</b> button to add a variation!</div>
@endif
</div>
</div>
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Project SEO Details (Optional)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">SEO Title: </label>
<input type="text" class="form-control" name="_seo_title" value="{{ old('_seo_title') }}" placeholder="SEO Title...">
</div>
<div class="form-group">
<label class="form-control-label active">SEO Tags: </label>
<input type="text" name="_seo_tags" value="{{ old('_seo_tags') }}" class="form-control rounded-0" id="seo_tags">
</div>
<div class="form-group">
<label class="form-control-label active">SEO Description: </label>
<textarea class="form-control" name="_seo_description" placeholder="SEO Description...">{{ old('_seo_description') }}</textarea>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('More Details (Required)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">Location: </label>
<input type="text" class="form-control" name="_location" value="{{ old('_location') }}" placeholder="Gaza, Palestine">
</div>
<div class="form-group">
<label class="form-control-label active">Active Status: </label>
<select class="form-control" name="active">
<option value="0" @if(old('active') == 0) selected @endif >Draft</option>
<option value="1" @if(old('active') == 1) selected @endif >Public</option>
<option value="2" @if(old('active') == 2) selected @endif >Private</option>
<option value="3" @if(old('active') == 3) selected @endif >Trash</option>
</select>
</div>
<hr>
<input class="btn btn-primary float-right" type="submit" value="Submit">
</div>
</div>
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Featured Media (Optional)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">Featured Image: </label>
<input class="form-control" name="featured_image" accept="image/*" type="file" id="featuredimageInput">
<div class="text-secondary"><small>Preferred Dimension: (720px) x (800px)</small></div>
</div>
<div class="form-group">
<label class="form-control-label active">Featured Image Alt: </label>
<input class="form-control" name="_alt" type="text" value="{{old('_alt')}}">
</div>
<div id="featuredimagePreview"></div>
<div class="form-group">
<label class="form-control-label active">Background Image: </label>
<input class="form-control" name="wallpaper_image" accept="image/*" type="file" id="Wallpaperimage">
<div class="text-secondary"><small>Preferred Dimension: (1920px) x (600px)</small></div>
</div>
<div id="WallpaperimagePreview"></div>
</div>
</div>
<div class="card mg-b-30">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div>
<h6 class="card-header-title tx-13 mb-0">{{ __('Project Category (Optional)') }}</h6>
</div>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-control-label active">Select Category:</label>
@if(sizeof($categories) > 0)
@foreach($categories as $category)
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="categories[]" value="{{$category->id}}" id="customCheck{{$category->id}}" @if(is_array(old('categories')) && in_array($category->id, old('categories'))) checked @elseif(old('categories') == $category->id) checked @endif>
<label class="custom-control-label" for="customCheck{{$category->id}}">{{$category->title}}</label>
</div>
@endforeach
@else
<p>No Project Category Found!</p>
@endif
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!--/ Order Active dataTable End -->
<!--================================-->
</div>
<!--/ Page Inner End -->
@include('Admin.Includes.footer')
<script>
$('.addTitle').on('input', function() {
var title = $(this).val();
var sku = title.replace(/\s+/g, '-').toLowerCase();
$('.permalink').val(sku);
validate_permalink();
});
$('.permalink').on('input', function() {
validate_permalink();
});
$('#short_description').summernote({
placeholder: 'Short Description...',
tabsize: 2,
height: 150,
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']]
]
});
$('#long_description').summernote({
placeholder: 'Long Description...',
tabsize: 2,
height: 250,
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['insert', ['link']],
['view', ['codeview']],
],
popover: {
image: [
['image', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']],
['float', ['floatLeft', 'floatRight', 'floatNone']],
['remove', ['removeMedia']]
],
link: [
['link', ['unlink']]
],
air: [
['color', ['color']],
['font', ['bold', 'underline', 'clear']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture']]
]
}
});
$('#seo_tags').tagsinput({ tagClass: 'badge badge-primary' });
// Get references to the input field and the div for image preview
var imageInput = document.getElementById('featuredimageInput');
var imagePreview = document.getElementById('featuredimagePreview');
// Get references to the input field and the div for image preview
var imageInput1 = document.getElementById('Wallpaperimage');
var imagePreview1 = document.getElementById('WallpaperimagePreview');
imageInput.addEventListener('change', function(event) {
var selectedFile = event.target.files[0];
if (selectedFile) {
var reader = new FileReader();
reader.onload = function(event) {
var imageElement = document.createElement('img');
imageElement.src = event.target.result;
imageElement.style.width = '100%';
imageElement.style.height = 'auto';
imagePreview.innerHTML = '';
imagePreview.appendChild(imageElement);
}
reader.readAsDataURL(selectedFile);
} else {
imagePreview.innerHTML = '';
}
});
imageInput1.addEventListener('change', function(event) {
var selectedFile = event.target.files[0];
if (selectedFile) {
var reader = new FileReader();
reader.onload = function(event) {
var imageElement = document.createElement('img');
imageElement.src = event.target.result;
imageElement.style.width = '100%';
imageElement.style.height = 'auto';
imagePreview1.innerHTML = '';
imagePreview1.appendChild(imageElement);
}
reader.readAsDataURL(selectedFile);
} else {
imagePreview1.innerHTML = '';
}
});
function validate_permalink(){
var permalink = $('#permalink').val();
$.ajax({
url: '{{route('Admin.Project.CheckPermalink')}}', // Replace with the actual route to handle the permalink check
method: 'POST',
data: { permalink: permalink, _token: $('meta[name="csrf-token"]').attr('content') },
dataType: 'json',
success: function(response) {
$('.permalink_status').val('1');
$('.permalink_error').html('');
},
error: function(xhr, status, error) {
console.log(xhr);
$('.permalink_status').val('');
$('.permalink_error').html('<small>This permalink already in used or field is empty!, Please change the permalink.</small>');
}
});
}
$(document).ready(function() {
// Add button click event
$('.add_variation_contatiner').click(function() {
$('.empty_variation_field').hide();
var index_V = $('.project_variation_container').length + 1;
$('.variations_backlog').append(`
<div class="border border-secondary rounded p-1 project_variation_container mb-3">
<div class="variation_img_box">
<button type="button" class="change-img-btn btn badge bg-primary">Change</button>
<img class="variation_img" src="/Placeholder.png">
<input type="file" accept="image/*" class="variation_img" name="variation_img_${index_V}" value="" style="display:none;">
<button type="button" class="remove-img-btn btn badge bg-warning"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
<div class="variations_inputs px-1 w-100">
<div class="input-group title_price_group">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Variation Title</span>
</div>
<input type="hidden" name="variations_count[]" value="variation">
<input type="text" class="form-control rounded-0 variation_title" name="variation_title_${index_V}" placeholder="Variation Title">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Price</span>
</div>
<input type="number" class="form-control rounded-0 variation_price" name="variation_price_${index_V}" placeholder="Price" value="0" min="0" step="0.01">
</div>
<div class="input-group description_group mt-2">
<div class="input-group-prepend rounded-0">
<span class="input-group-text rounded-0" id="">Description</span>
</div>
<input type="text" class="form-control rounded-0 variation_description" name="variation_description_${index_V}" placeholder="Description...">
</div>
<button type="button" class="remove_variation btn btn-sm btn-danger p-1"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
</div>
`);
// Update variation names
updateVariationNames();
});
$('.variations_backlog').on('click', '.remove_variation', function() {
$(this).parent().parent().remove();
if($('.project_variation_container').length < 1){
$('.empty_variation_field').show();
}
// Update variation names
updateVariationNames();
});
// Event delegation for change button click event
$('.variations_backlog').on('click', '.change-img-btn', function() {
$(this).siblings('input[type="file"]').trigger('click');
});
// Event delegation for file input change event
$('.variations_backlog').on('change', 'input[type="file"]', function() {
var input = $(this);
var file = input[0].files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = input.siblings('.variation_img');
img.attr('src', e.target.result);
};
reader.readAsDataURL(file);
}
});
// Event delegation for remove button click event
$('.variations_backlog').on('click', '.remove-img-btn', function() {
var img = $(this).siblings('.variation_img');
var input = $(this).siblings('input[type="file"]');
img.attr('src', '/Placeholder.png');
input.val('');
});
});
// Function to update variation names
function updateVariationNames() {
$('.project_variation_container').each(function(index) {
var variationContainer = $(this);
var variationImgInput = variationContainer.children('.variation_img_box').children('.variation_img');
var variationTitleInput = variationContainer.children('.variations_inputs').children('.title_price_group').children('.variation_title');
var variationPriceInput = variationContainer.children('.variations_inputs').children('.title_price_group').children('.variation_price');
var variationDescriptionInput = variationContainer.children('.variations_inputs').children('.description_group').children('.variation_description');
// Update input names
variationImgInput.attr('name', `variation_img_${index + 1}`);
variationTitleInput.attr('name', `variation_title_${index + 1}`);
variationPriceInput.attr('name', `variation_price_${index + 1}`);
variationDescriptionInput.attr('name', `variation_description_${index + 1}`);
});
}
</script>
Controller
public function store(Request $request){
try{
$logged_in_user = Auth::user();
$stdout = fopen('php://stdout', 'w');
DB::table('project_temp_variation')->where('user_id' , $logged_in_user->id)->delete();
if (isset($request->variations_count)) {
$i = 1;
$variations = [];
foreach ($request->variations_count as $count) { // Rename the loop variable
$title = 'variation_title_'.$i;
$price = 'variation_price_'.$i;
$description = 'variation_description_'.$i;
$thumbnail = 'variation_img_'.$i;
if ($request->hasFile($thumbnail)) {
$image = $request->file($thumbnail);
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('temp'), $imageName);
$manager = new ImageManager();
$optimizedImage = $manager->make(public_path('temp') . '/' . $imageName)
->fit(800, 800) // Adjust the dimensions as needed
->encode();
$optimizedImage->save(public_path('projects/variations') . '/' . $imageName);
unlink(public_path('temp') . '/' . $imageName);
$thumbnail = 'projects/variations/' . $imageName;
}else{
$thumbnail = '';
}
$variations[$i] = [
'user_id' => $logged_in_user->id,
'title' => $request->$title,
'price' => $request->$price,
'description' => $request->$description,
'thumbnail' => $thumbnail
];
$i++;
}
if(DB::table('project_temp_variation')->insert($variations)){
fwrite($stdout, 'Project Variations Stored to temporary table');
}else{
fwrite($stdout, 'Project Variations not Stored to temporary table');
}
}
$validatedData = $request->validate([
'project_title' => 'required|string',
'permalink' => 'required|string|unique:products,permalink',
'short_description' => 'nullable|string',
'long_description' => 'nullable|string',
'featured_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:3078',
'active' => 'nullable|integer',
]);
if ($request->filled('categories')) {
$validatedData['categories'] = implode(',', $request->input('categories', []));
}
if ($request->hasFile('featured_image')) {
$image = $request->file('featured_image');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('temp'), $imageName);
$manager = new ImageManager();
$optimizedImage = $manager->make(public_path('temp') . '/' . $imageName)
->fit(720, 800) // Adjust the dimensions as needed
->encode();
$optimizedImage->save(public_path('projects') . '/' . $imageName);
unlink(public_path('temp') . '/' . $imageName);
$validatedData['featured_image'] = 'projects/' . $imageName;
}
if ($request->hasFile('wallpaper_image')) {
$image = $request->file('wallpaper_image');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('temp'), $imageName);
$manager = new ImageManager();
$optimizedImage = $manager->make(public_path('temp') . '/' . $imageName)
->fit(1920, 600) // Adjust the dimensions as needed
->encode();
$optimizedImage->save(public_path('projects') . '/' . $imageName);
unlink(public_path('temp') . '/' . $imageName);
$validatedData['background_image'] = 'projects/' . $imageName;
}
$validatedData['created_by'] = $logged_in_user->id;
$project = Project::create($validatedData);
$metaDescriptions = $request->only([
'_seo_title',
'_seo_tags',
'_seo_description',
'_alt',
'_location',
]);
$projectMeta = [];
foreach ($metaDescriptions as $option => $value) {
if ($value !== null) {
$projectMeta[] = [
'project_id' => $project->id,
'option' => $option,
'value' => $value,
'created_at' => now(),
'updated_at' => now(),
];
}
}
# Insert project meta descriptions in bulk
DB::table('projects_meta')->insert($projectMeta);
$now_time = now();
// Move data from temporary table to main table with project_id
DB::statement("INSERT INTO projects_donation_variation (project_id, title, description, price, thumbnail, created_at, updated_at)
SELECT $project->id, title, description, price, thumbnail, '$now_time', '$now_time'
FROM project_temp_variation
WHERE user_id = $logged_in_user->id");
// Delete data from temporary table
DB::table('project_temp_variation')->where('user_id', $logged_in_user->id)->delete();
return redirect()->route('projects.create')->with(['success' => 'Project created successfully!']);
} catch (\Exception $e) {
$error = $e->getMessage();
return redirect()->back()->with(['error' => $error]);
}
}