How to Save an array index data to database in separate row? - php

I have a featureds table (foreign key= product_id) that belongsto products table, Now i want to save some products id to my featured table,its give me a array reasult but i couldnot save it to database
Here is my Controller -->
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')){
$product_id=$request->all();
foreach ($product_id as $product) {
$products[]=$product;
}
//dd($products);
Featured::create($products);
}
return view('admin.products.featured');
}
<form action="{{ route('featuredProduct') }}" method="POST" multiple>
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap verticle_middle">
<thead>
<tr>
<th>Product</th>
<th>Category</th>
<th>Image</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#foreach ($products as $product)
<tr>
<td>
<input id="{{ $product->id }}" value="{{ $product->id }}" type="checkbox" name="product[]">
<label for=id={{ $product->id }}>{{ $product->product_name }}</label>
</td>
<td> {{ $product->category['cat_name'] }} </td>
<td> <img src="{{asset($product->pro_img) }}" alt="" width="40"> </td>
<td class="center">
#if ($product->status === 1)
<span class="btn btn-primary btn-xs">Published</span>
#else
<span class="btn btn-warning btn-xs">Unpublish</span>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="modal-footer">
<button type="button"class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary waves-effect waves-light">Submit</button>
</div>
</form>

You can create each feature inside the for loop.
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')) {
foreach($request->all() as $productId) {
Featured::create([
'product_id' => $productId,
... other data fields.
]);
}
}
}
Or if you want to save all the features at once.
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')) {
$featureds = [];
foreach($request->all() as $productId) {
$featureds[] = [
'product_id' => $productId,
... other data fields.
]
}
DB::table('featureds')->insert($featureds);
}
}

Related

After selecting one person, selected person must dissappear from options

In the group table I select a person from the list, but after selecting one name, his name should not appear in other select options, it must show 'selected' or just disappear, so names in groups cant duplicate, 1name=1slot.
In the students list below, there must be a group's name assigned to a person if he/she is selected.
View for a better understanding
My groups dropdown blade:
<div class="row">
#for ($groupName = 1; $groupName <= $project->amount; $groupName++)
<div class="col-3">
<table class="table table-bordered table-sm table-hover text-center my-3">
<tr class="table-light">
<th> Group #{{ $groupName }} </th>
</tr>
<tr>
<td>
#for ($j = 0; $j < $project->studentsPerGroup; $j++)
<select class="form-select form-select-sm" style="overflow:auto; max-height:260;">
<option selected>Assign Student</option>
#foreach ($students as $student)
<option value="{{ $groupName }}">{{ ucwords($student->name) }} {{ $loop->iteration . '/' . $loop->count }}</option>
#endforeach
</select>
#endfor
</td>
</tr>
</table>
</div>
#endfor
</div>
And persons list table:
enter code her<table class="table table-bordered table-sm table-hover text-center my-3">
<tr class="table-light">
<th>Student</th>
<th>Group Name</th>
<th width="220px">Action</th>
</tr>
#foreach ($students as $student)
<tr class="align-middle">
<td class="text-left">{{ ucwords($student->name) }}</td>
<td>Group#</td>
<td>
<form action="{{ route('students.destroy', $student->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" title="delete" class="btn btn-danger btn-sm" onclick="return confirm('Please Confirm')">
Remove
</button>
</form>
</td>
</tr>
#endforeach
</table>
It's a school project and I really tried hard. Any help is appreciated.

i want to check all my checkbox from one checkbox using laravel 8 mvc

I want to check the first checkbox that have the id checkAll and it will check all my checkboxes and when I unchecked it, it will unchecked all too.
My blade index.blade.php:
<body>
<table class="table">
<thead>
<tr>
<th scope="col">
<input type="checkbox" id="checkAll">
</th>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">Paragraph</th>
</tr>
</thead>
#foreach ($categories as $categorie)
<tbody>
<tr>
<td>
<input type="checkbox" name="checkOne" value="{{$categorie->id}}">
</td>
<th scope="row">{{ $categorie->id }}</th>
<td>{{ $categorie->Title }}</td>
<td>{{ $categorie->Paragraph }}</td>
<form action={{ route('categorie.destroy', $categorie->id) }} method="POST">
#csrf
#method('DELETE')
<td>
<button class="btn btn-danger" type="submit">
delete
</button>
</form>
<button class="btn btn-warning"> <a href={{ route('edit', $categorie->id) }}>edit</a> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
</body>
If you have multiple checkboxes with the same name then use array in your loop, as below:
<input type="checkbox" name="checkOne[]" value="{{ $categorie->id }}">
Now you need to use jQuery to select/unselect checkboxes, use below code:
$('#checkAll').change(function() { // main checkbox id
$('input[name="checkOne[]"]').prop('checked', $(this).is(":checked"));
});
Try this code -
<script type='text/javascript'>
function checkAll(e) {
const checkboxes = document.getElementsByName('checkOne');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = e.checked;
}
}
</script>

can I use my controller in laravel 8 to delet row that checked in view?

#extends('layouts.app')
#section('content')
<body>
<button class="btn" onclick="deleteSelected()">delete</button>
<table class="table">
<thead>
<tr>
<th scope="col">
<input type="checkbox" id="all" onclick="chkd()">
</th>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">Paragraph</th>
</tr>
</thead>
#foreach ($categories as $categorie)
<tbody>
<tr>
<td>
<input type="checkbox" class="ss" value="{{ $categorie->id }}" onclick="deleteSelected()">
</td>
<th scope="row">{{ $categorie->id }}</th>
<td>{{ $categorie->Title }}</td>
<td>{{ $categorie->Paragraph }}</td>
<form action={{ route('categorie.destroy', $categorie->id) }} method="POST">
#csrf
#method('DELETE')
<td>
<button id="deleteRow" class="btn btn-danger" type="submit" style="display: none">
delete
</button>
</form>
<button class="btn btn-warning"> <a href={{ route('edit', $categorie->id) }}>edit</a> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
</body>
#endsection
that is my view , when I check one of my checkbox and press the button delete I want this row to be deleted or when I checked all I want to delete all row
I think html input must inside the form. How about moving code like this:
#foreach ($categories as $categorie)
<tbody>
<tr>
<td>
<form action={{ route('categorie.destroy', $categorie->id) }} method="POST">
#csrf
#method('DELETE')
<input type="checkbox" class="ss" value="{{ $categorie->id }}" onclick="deleteSelected()">
<button id="deleteRow" class="btn btn-danger" type="submit" style="display: none">
delete
</button>
</form>
</td>
<th scope="row">{{ $categorie->id }}</th>
<td>{{ $categorie->Title }}</td>
<td>{{ $categorie->Paragraph }}</td>
<td><button class="btn btn-warning"> <a href={{ route('edit', $categorie->id) }}>edit</a> </button></td>
</tr>
</tbody>
#endforeach
But, I don't know this is can fix your case or not. I can't see the whole code

How to show image using storage folder for looping data

My image is not displaying. I'm using Storage:: to save my image. Here how my folder looks like and php artisan storage:link has been created. I already try this code {{ asset('storage/complaint' . $c->image)}},{{ storage_path() . '/complaint' .$c->image}}and {{ url('/public/complaint' . $c->image) }} but it seems to be not working at all.
web.php
Route::get('/report-form','ComplaintController#create');
Route::post('/report-create','ComplaintController#store');
Route::get('/report-view','ComplaintController#index');
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Validator;
use Response;
use Carbon\Carbon;
use App\Complaint;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Intervention\Image\ImageManagerStatic as Image;
class ComplaintController extends Controller
{
public function index(Request $request)
{
if (Auth::user()->role == 'buyer')
{
$complaint = Complaint::where('report_by',Auth::user()->id)->get();
return view('buyers.complaints.index',compact('complaint'));
}
}
public function create(Request $request)
{
return view('buyers.complaints.create');
}
public function store(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
if (isset($request->image[$item])) {
$images = $request->file('image');
$image_resize = Image::make($images[$item]->getRealPath());
$image_resize->resize(900, 630);
$filename = $images[$item]->getClientOriginalName();
Storage::put($filename, $image_resize);
Storage::move($filename, 'public/complaint/' . $filename);
}
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $filename,
'description' => $request->description[$item],
'report_by' => Auth::user()->id,
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString()
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
create.blade.php
<div class="panel">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
<br>
</form>
</div>
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += '<td><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += '<td><input type="file" class="form-control-file" name="image[]"></td>';
html += '<td><input type="text" class="form-control" name="description[]"></td>';
html += '<td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop
index.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>List of Report</strong></h3>
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Defect Name</th>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
#foreach($complaint as $c)
<tr class="">
<td>{{$c->defect->name}}</td>
<td>{{$c->description}}</td>
<td><img src="{{ asset('storage/complaint' . $c->image)}}" class="" alt="{{$c->image}}"></td>
</tr>
#endforeach
</table>
</div>
What is my mistakes?
use Storage::url() ref link https://laravel.com/docs/8.x/filesystem#file-urls
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
NOTE: make sure APP_URL=http://exmaplet.test this is set

Deleting selected rows from checkbox in laravel

I have a table with its data are retrieved from database here: https://imgur.com/Sv4Suo7 . My problem is, I want to delete the data that are selected in the checkboxes.
I have tried putting name="ids[]" in my checkbox, but the data is still not sent to my controller. I have read somewhere that I need to use Javascript, but I don't know how to.
Views:
<div class="box-header with-border">
<div class="box-header-tools pull-left" >
<a href="{{ url('tasks/create/')}}" class="tips text-green" title="{{ Lang::get('core.btn_create') }} ">
<i class="fa fa-plus-square-o fa-2x"></i></a>
<a href="{{ url('tasks/massDelete')}}" onclick="" class="tips text-red" title="{{ Lang::get('core.btn_remove') }}">
<i class="fa fa-trash-o fa-2x delete_all" data-toggle="confirmation" data-title="{{Lang::get('core.rusure')}}" data-content="{{ Lang::get('core.rusuredelete') }}" ></i></a>
</div>
</div>
<div class="box-body" >
<div class="table-responsive" style="min-height:300px; padding-bottom:60px; border: none !important">
<table class="table table-striped table-bordered " id="{{ $pageModule }}Table">
<thead>
<tr>
<th align="center" class="number"> No </th>
<th align="center"> <input type="checkbox" class="checkall" id="master" /></th>
<th align="center">Task</th>
<th align="center">Due Date</th>
<th align="center">Assigned To</th>
<th align="center">Assigned By</th>
<th align="center">Status</th>
<th align="center">{{ Lang::get('core.btn_action') }}</th>
</tr>
</thead>
<tbody> #foreach($tasks as $task)
<tr>
<td width="30"> {{ ++$i }} </td>
<td width="50"><input type="checkbox" class="checkbox" name="ids[]" value="{{$task->id}}" /></td>
<td>{{$task->task_name}} </td>
<td>{{$task->due_date}}</td>
#foreach($users as $user)
#if($user->id == $task->assigned_id)<td>{{$user->username}}</td>#endif
#endforeach
#foreach($users as $user)
#if($user->id == $task->assigner_id)<td>{{$user->username}}</td>#endif
#endforeach
#if($task->status == 0)<td width="90">
<span class="label label-block label-info label-sm">Ongoing</span>
</td>#endif
#if($task->status == 1)<td width="90">
<span class="label label-block label-danger label-sm">Cancelled</span>
</td>#endif
#if($task->status == 2)<td width="90">
<span class="label label-block label-success label-sm">Completed</span>
</td>#endif
<td>
#if($task->status == 0)
{!! Form::open(array('url'=>'tasks/completeStatus/'.$task->id, 'class'=>'form-horizontal')) !!}
<button type="submit" name="markcomplete" class="btn" ><i class="fa fa-check-circle-o fa-2x"></i></button>
{!! Form::close() !!}
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
<input type="hidden" name="md" value="" />
</div>
</div>
</div>
</div>
Controller:
public function massDelete(Request $request)
{
$gotids = $request->input('ids');
if($gotids){
foreach($gotids as $id){
$task = Tasks::findOrFail($id);
$task->delete();
}
}
return redirect('tasks');
}
Route:
Route::get('/tasks/massDelete/', 'TasksController#massDelete');
I wanted the data to be in controller, when I tried dd($gotids); it displays null. Hope anyone can help.
Here is the code if you want to use javascript
Route::delete('delete-multiple-category', ['as'=>'category.multiple-delete','uses'=>'CategoryController#deleteMultiple']);
public function deleteMultiple(Request $request){
$ids = $request->ids;
Category::whereIn('id',explode(",",$ids))->delete();
return response()->json(['status'=>true,'message'=>"Category deleted successfully."]);
}
blade file
<div class="container">
<h3>PHP Laravel 5.6 - How to delete multiple row with checkbox using Ajax? - HDTuto.com</h3>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
<table class="table table-bordered">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>Category Name</th>
<th>Category Details</th>
<th width="100px">Action</th>
</tr>
#if($categories->count())
#foreach($categories as $key => $category)
<tr id="tr_{{$category->id}}">
<td><input type="checkbox" class="checkbox" data-id="{{$category->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $category->category_name }}</td>
<td>{{ $category->category_details }}</td>
<td>
{!! Form::open(['method' => 'DELETE','route' => ['category.destroy', $category->id],'style'=>'display:inline']) !!}
{!! Form::button('Delete', ['class' => 'btn btn-danger btn-xs','data-toggle'=>'confirmation','data-placement'=>'left']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
#endif
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
$('.delete-all').on('click', function(e) {
var idsArr = [];
$(".checkbox:checked").each(function() {
idsArr.push($(this).attr('data-id'));
});
if(idsArr.length <=0)
{
alert("Please select atleast one record to delete.");
} else {
if(confirm("Are you sure, you want to delete the selected categories?")){
var strIds = idsArr.join(",");
$.ajax({
url: "{{ route('category.multiple-delete') }}",
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+strIds,
success: function (data) {
if (data['status']==true) {
$(".checkbox:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['message']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.closest('form').submit();
}
});
});
</script>

Categories