Getting input from multiple forms by modal in laravel - laravel

Im pretty new to web development, im creating basic CRUD for my intern project. My client asked me to make a single create form where i need to upload those input to database, lets say i have 3 table : Shops,Fruits (one shop has many fruits), and Vegetables (one shop has many vegetables)
I ended up making multiple forms, which one main form for the shop input, and some additional form inside modal for fruits and vegetables input (forms are separated).
After submitting and passing to controller, i can only get input from shop form and not the others.
Scripts and styles:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//Adding and removing fruit table row
$(".fruit-add").click(function(){
var fruit_pic = $("#fruit_pic").val();
var fruit_pic_name = $("#fruit_pic").val().replace(/C:\\fakepath\\/i, '')
var fruit_name = $("#fruit_name").val();
var markup = "<tr><td>" + fruit_pic_name + "</td><td>" + fruit_name + "</td><td>" + "<button type='button' class='fruit-remove'> Delete </button>" + "</td></tr>";
$(".fruit-table").append(markup);
});
$("body").on("click",".fruit-remove",function(){
$(this).parents("tr").remove();
});
//Adding and removing vegetable table row
$(".vegetable-add").click(function(){
var vegetable_pic = $("#vegetable_pic").val();
var vegetable_pic_name = $("#vegetable_pic").val().replace(/C:\\fakepath\\/i, '')
var vegetable_name = $("#vegetable_name").val();
var markup = "<tr><td>" + vegetable_pic_name + "</td><td>" + vegetable_name + "</td><td>" + "<button type='button' class='vegetable-remove'> Delete </button>" + "</td></tr>";
$(".vegetable-table").append(markup);
});
$("body").on("click",".vegetable-remove",function(){
$(this).parents("tr").remove();
});
});
</script>
My shop form:
<form method="post" action="/add-shop/store" id="addShop" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="shop_name">Shop name</label>
<input type="text" class="form-control" name="shop_name" id="shop_name" aria-describedby="shop_name">
#if($errors->has('shop_name'))
<div class="text-danger">
{{ $errors->first('shop_name')}}
</div>
#endif
</div>
<div class="form-group">
<label> Fruits </label>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Picture</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody class="fruit-table">
</tbody>
</table>
</div>
<!-- Button trigger fruit modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addFruit">
Add fruit
</button>
</div>
<div class="form-group">
<label> Vegetables </label>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Picture</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody class="vegetable-table">
</tbody>
</table>
</div>
<!-- Button trigger vegetable modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addVegetable">
Add vegetable
</button>
</div>
<div class="form-group text-right">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
My forms on popup modal:
<!-- Fruit Modal -->
<div class="modal fade" id="addFruit" tabindex="-1" role="dialog" aria-labelledby="addFruit" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_fruit">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addFruit">Fruit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="fruit_pic">Picture</label>
<input type="file" accept="image/*" name="fruit_pic[]" id="fruit_pic" class="form-control">
</div>
<div class="form-group">
<label for="fruit_name">Name</label>
<input type="text" name="fruit_name[]" class="form-control" id="fruit_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary fruit-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
<!-- Vegetable Modal -->
<div class="modal fade" id="addVegetable" tabindex="-1" role="dialog" aria-labelledby="addVegetavle" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_vegetable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVegetable">Vegetable</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="vegetable_pic">Picture</label>
<input type="file" accept="image/*" name="vegetable_pic[]" id="vegetable_pic" class="form-control">
</div>
<div class="form-group">
<label for="vegetable_name">Name</label>
<input type="text" class="form-control" name="vegetable_name[]" id="vegetable_name" placeholder="Deskripsi">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary vegetable-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
controller functions:
public function add()
{
return view('add-shop');
}
public function storeTest(Request $request)
{
echo "test\n"; //works
echo $request->fruit_name; //doest work
if($request->hasfile('fruit_pic')){ //doesnt work
foreach($request->file('fruit_pic') as $image){
echo $request->fruit_name;
}
}
echo $request->shop_name; //work
}
When i try to submit the form, i get the shop_name but not all the other form attributes (fruits and vegetables)
I have the feeling that my method is not quite right, what is wrong and is there a better way to applicate this?

just taking a quick look at the form you should use at the action
{{url(}}
{{route()}}
your not getting the shop form because the model it self is not in the form make sure to put it in the same form where you submit the original form tag. alternative if you really want to have it outside you can make a hidden input in the form and put there your data in with java script from the model and then submit the form

do this also to the --vegetable modal--:
<!-- Fruit Modal -->
<div class="modal fade" id="addFruit" tabindex="-1" role="dialog" aria-labelledby="addFruit" aria-hidden="true">
<div class="modal-dialog" role="document">
<form id="form_fruit" method="post" action="{{ url('/add-fruits') }}">
{{ csrf_field() }}
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addFruit">Fruit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="fruit_pic">Picture</label>
<input type="file" accept="image/*" name="fruit_pic[]" id="fruit_pic" class="form-control">
</div>
<div class="form-group">
<label for="fruit_name">Name</label>
<input type="text" name="fruit_name" class="form-control" id="fruit_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary fruit-add" data-dismiss="modal">Add</button>
</div>
</div>
</form>
</div>
</div>
controller
public function addFruits(Request $request)
{
$this->validate($request, [
'fruit_name' => 'required|string',
'fruit_pic.*' => 'mimes:jpeg,jpg,gif,png,bmp|max:8300',
]);
$fruitname=$request->input('fruit_name');
if($request->hasfile('fruit_pic'))
{
foreach($request->file('fruit_pic') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/../../example.com/images', $name);
DB::table('tblfruits')->insert([
'fruit_name' => $fruitname,
'fruit_pic' => $name,
]);
}
}
}
route
Route::post('/add-fruits','Controller#addFruits');

Related

Laravel 5.5 - MethodNotAllowedHttpException

I have an task using Laravel. Which one on my task, user can edit the data on master data table. I'm using modal pop when user want to edit the data. So the user no need to move the page for edit data. On my task I'm using Laravel 5.5
Here is my code :
This is for tabel modal edit
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header no-bd">
<h5 class="modal-title">
<span class="fw-mediumbold">Detail</span>
<span class="fw-light">Data</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-material form-horizontal" method=post action="{{route('masterdataobjek.update', 'test')}}">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<input type="hidden" name="id_objek" id="id_objek_modal" value="">
<div class="form-group form-group-default">
<label>Nama Objek</label>
<input id="objek_nama_modal" type="text" name="objek_nama_modal" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group form-group-default">
<label for="comment">Deskripsi Objek</label>
<textarea class="form-control" name="objek_desc_modal" id="objek_desc_modal" rows="5"></textarea>
</div>
</div>
<div class="col-sm-12">
<label for="exampleFormControlFile1">Upload WTO File</label>
<div class="form-group form-group-default">
<input type="file" class="form-control-file" name="objek_wto" id="objek_wto">
</div>
</div>
</div>
<div class="modal-footer no-bd">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
For the button clicked code ;
<tbody>
#foreach ($tabelobjek as $ta => $data)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $data->objek_nama}}</td>
<td style="">{{str_limit($data->objek_desc,15)}}</td>
<td>
<div class="form-button-action">
<button type="button" data-toggle="modal"
class="btn btn-link btn-success btn-lg" data-original-title="Edit"
data-target="#edit-modal" id="edit-button"
data-idobjek="{{$data->id_objek}}"
data-namaobjek="{{$data->objek_nama}}"
data-objekdeskripsi="{{$data->objek_desc}}">
<i class="fa fa-edit"></i>
</button>
</div>
</td>
</tr>
#endforeach
</tbody>
for trigger button :
<script>
$(document).ready(function () {
$(document).on('click', '#edit-button', function () {
var namaobjek = $(this).data('namaobjek');
var objekdeskripsi = $(this).data('objekdeskripsi');
var idobjek = $(this).data(idobjek)
$('#id_objek_modal').val(idobjek)
$('#objek_nama_modal').val(namaobjek);
$('#objek_desc_modal').val(objekdeskripsi);
})
})
MasterDataObjekController.php
public function update(Request $request)
{
$updateObjek = TbObjek::findOrFail($request->id_objek);
$updateObjek->update($request->all());
return back();
}
POST requests are for creating new records, PUT and PATCH are for updating records. Refer to the table of HTTP methods on Laravel RESTful containers here
You need to change your form tag from this
<form class="form-material form-horizontal" method=post action="{{route('masterdataobjek.update', 'test')}}">
to this
<form class="form-material form-horizontal" method="put" action="{{route('masterdataobjek.update', 'test')}}">

Problem with Passing data from Laravel controller to Boostrap Modal

Hello everyone one i have a problem . I want to pass data from my Controller to my modal . I have a list of categories i want to display it in a dropdown list i've tried using href attribute and ajax but none of these worked is there any solution ?
here is a piece of code :
List of all Categories blade.php :
#extends('layouts.Template')
#section('content')
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<center> <h2 class="page-title">Gérer les Sous Catégories</h2> </center>
<div class="panel panel-default">
<div class="panel-heading"> <strong>Liste Sous Catégories</strong></div>
<div class="panel-body">
<table id="zctb" class="table table-bordered">
<tr>
<th>Id</th>
<th>Nom</th>
<th>Nom de Catégories</th>
<th>image</th>
<th>created_at</th>
<th>updated_at</th>
<a class="fas fa-plus-circle" style="font-size:60px;color:#e2ccae;margin-left:90%;"href="{{url ('/Sous_Catégories/ajouter')}}"></a>
</tr>
#foreach($Souscategories as $Scategorie)
<tr>
<td>{{$Scategorie->id}}</td>
<td>{{$Scategorie->nom}}</td>
<td>{{$Scategorie ->nomCat}}</td>
<td>{{$Scategorie->image}}</td>
<td>{{$Scategorie -> created_at}}</td>
<td>{{$Scategorie -> updated_at}}</td>
<td ><a class="fas fa-edit" href="{{ route('Sous_Catégories.getAllCategories')}}" data-nom="{{$Scategorie->nom}}" data-nomCat="{{$Scategorie->nomCat}}" data-image="{{$Scategorie->image}}" data-cat_id1 ="{{$Scategorie->id }}" data-toggle="modal" data-target="#edit1">Edit</a></td>
<td><a class="fas fa-trash" href="{{url ('/Sous_Catégories/supp',[$Scategorie->id])}}" > </td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modifier Sous Catégories</h4>
</div>
<form action="{{ route('Sous_Catégories.update','test')}}" method="POST">
{{method_field('patch')}}
{{csrf_field()}}
<div class="modal-body">
<input type="hidden" name="cat_id1" id="cat_id1" value="">
#include('formSousCat')
</div>
<div class="modal-footer">
<button id="fermer" type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button id="save" type="submit" class="btn btn-primary">Enregistrer</button>
</div>
</form>
</div>
</div>
</div>
#endsection
controller Methode :
public function getAllCategories()
{
$Cat = categories::all();
return view('formSousCat', compact('Cat'));
}
My routers :
Route::get('/Sous_Catégories', 'SousCatController#index' );
Route::post('/Sous_Catégories/ajouter', 'SousCatController#create');
Route::get('/Sous_Catégories/supp/{id}', 'SousCatController#destroy');
Route::get('/Sous_Catégories/getAllCategories', 'SousCatController#getAllCategories');
Route::resource('Sous_Catégories', 'SousCatController');
My Modal.blade
<label>Nom</label>
<input id="nom" name="nom" class="form-control"type="text"/>
</div>
<br/>
<div>
<label for="le_nom">Choix de categorie</label><br />
<label for="le_nom">Choix de categorie</label><br />
<select name="le_nom" id="le_nom" class="form-control">
#foreach($Cat as $categorie) <!-- $Cat is undefined -->
<option class="form-control">{{$categorie->nomCat}}</option>
#endforeach
</select>
<div class="input-group">
<div class="custom-file">
<div class="form-group">
<input type="file" name="image" class="form-control-file">
</div>
</div>
You can use a click event on a button tag, to opent the modal and initiate an ajax request which fetches the data from the controller and inserts into the categories.
<button id="openModal">Open Modal</button>
In your controller:
public function getAllCategories()
{
$Cat = categories::all();
return response()->json($cat);
}
In your script
let btn = document.querySelector('#openModal')
let slct = document.querySelector('#le_nom')
btn.addEventListener('click', function(){
$.ajax({
url: '{{url("/Sous_Catégories/getAllCategories")}}',
method: 'GET',
success: function(response){
response.Foreach((op) = > {
slct.innerHTML += `<option value="${op.id}">${op.nomCat}</option>`
})
}
})
})

Form submit using bootstrap modal without jquery and display event in calendar

I have successfully submitted form using bootstrap modal in laravel.Now I want to display the data in the calendar according to date.I have tried but unable to get the event in the calendar days.
event.blade.php
css
<link href="{{asset('admin-panel/assets/libs/fullcalendar/dist/fullcalendar.min.css')}}" rel="stylesheet" />
<link href="{{asset('admin-panel/assets/extra-libs/calendar/calendar.css')}}" rel="stylesheet" />
<link href="{{asset('admin-panel/dist/css/style.min.css')}}" rel="stylesheet">
<script src="{{asset('admin-panel/assets/libs/jquery/dist/jquery.min.js')}}"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="">
<div class="row">
<div class="col-lg-3 border-right p-r-0">
<div class="card-body border-bottom">
<h4 class="card-title m-t-10">Drag & Drop Event</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div id="calendar-events" class="">
<div class="calendar-events m-b-20" data-class="bg-info"><i class="fa fa-circle text-info m-r-10"></i>Event</div>
<div class="calendar-events m-b-20" data-class="bg-success"><i class="fa fa-circle text-success m-r-10"></i>Event</div>
<div class="calendar-events m-b-20" data-class="bg-danger"><i class="fa fa-circle text-danger m-r-10"></i>Event</div>
<div class="calendar-events m-b-20" data-class="bg-warning"><i class="fa fa-circle text-warning m-r-10"></i>Event</div>
</div>
<!-- checkbox -->
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="drop-remove">
<label class="custom-control-label" for="drop-remove">Remove after drop</label>
</div>
<a href="javascript:void(0)" data-toggle="modal" data-target="#add-new-event" class="btn m-t-20 btn-info btn-block waves-effect waves-light">
<i class="ti-plus"></i> Add New Event
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-9">
<div class="card-body b-l calender-sidebar">
<div id="calendar"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- BEGIN MODAL -->
<div class="modal none-border" id="my-event">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><strong>Add Event</strong></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary waves-effect" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success save-event waves-effect waves-light">Create event</button>
<button type="button" class="btn btn-danger delete-event waves-effect waves-light" data-dismiss="modal">Delete</button>
</div>
</div>
</div>
</div>
<!-- Modal Add Category -->
<div class="modal fade none-border" id="add-new-event">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><strong>Add</strong> Event</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<form action="{{route('event.store')}}" method="post">
#csrf
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<label class="control-label">Date</label>
<input class="form-control form-white" name="date" type="date"/>
</div>
<div class="col-md-6">
<label class="control-label">Event Name</label>
<input class="form-control form-white" name="event" placeholder="Enter name" type="text"/>
<br>
</div>
<div class="col-md-12">
<label class="control-label">Description</label>
<input class="form-control form-white" name="description" placeholder="Enter description" type="text"/>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger waves-effect waves-light save-category">Save</button>
<button type="button" class="btn btn-secondary waves-effect" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
javascript
#section('js')
<script src="{{asset('admin-panel/assets/libs/jquery/dist/jquery.min.js')}}"></script>
<script src="{{asset('admin-panel/dist/js/jquery-ui.min.js')}}"></script>
<script src="{{asset('admin-panel/assets/libs/bootstrap/dist/js/bootstrap.min.js')}}"></script>
<script src="{{asset('admin-panel/dist/js/custom.min.js')}}"></script>
<script src="{{asset('admin-panel/assets/libs/moment/min/moment.min.js')}}"></script>
<script src="{{asset('admin-panel/assets/libs/fullcalendar/dist/fullcalendar.min.js')}}"></script>
<script src="{{asset('admin-panel/dist/js/pages/calendar/cal-init.js')}}"></script>
#endsection
EventController.php
public function event()
{
$events=$this->getEventbyMonth(date('m'));
// dd($events);
return view('admin.calendar.event',compact('events'));
}
public function store(Request $request)
{
// dd($request->all);
$request -> validate([
'date' => 'required',
'event' => 'required',
]);
$event = new Event();
$event -> date = $request -> date;
$event -> event = $request -> event;
$event -> description = $request -> description;
$event ->save();
return redirect()->route('event');
}
private function getEventbyMonth($month)
{
return Event::whereMonth('date',$month)->get();
}
and my route look like this:
Route::get('event', ['as'=>'event', 'uses' => 'EventController#event']);
Route::post('event/store, ', ['as'=>'event.store', 'uses' => 'EventController#store']);
Expected results:
Imgur
Actual results:
Imgur
Database:
Imgur
Event form after clicking add new event
Imgur

How can i resolve my update record query in same page?

In My list view I have all the details of department. But when I click on details It will display me a Pop-up. In Pop up box it has to fetch and give me all the details of particular field but instead of that it always give me details of last inserted record
Here is my code of blade file
#extends('layouts.master')
#section('content')
<section>
<div class="page-wrapper">
<div class="container-fluid">
<div class="row page-titles">
<div class="col-md-5 align-self-center">
<h4 class="text-themecolor">{{__('Department')}}</h4>
</div>
</div>
<div class="card">
<div class="card-body">
<div>
+ Add Department
</div>
<div id="myModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add Department </h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<form id="myform" class="form-horizontal" method="POST" action="{{route('store_department')}}">
#csrf
<div class="form-group">
#if(Session::has('key'))
<?php $createdBy = Session::get('key')['username']; ?>
#endif
<div class="col-md-12">
<input type="hidden" name="createdBy" value="<?php echo $createdBy ?>">
<input type="text" class="form-control" name="nameOfDepartment" placeholder="Add New Department">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info waves-effect" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<div class="table-responsive m-t-40">
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>Department Name</th>
<th>Created By</th>
<th>Created On</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($listOfDepartment != null)
#foreach($listOfDepartment as $departmentList)
<tr>
<td>{{$departmentList->nameOfDepartment}}</td>
<td>{{$departmentList->createdBy}}</td>
<td>{{$departmentList->created_at}}</td>
<td>
<i class="fa fa-edit fa-lg" style="color:#0066ff" aria-hidden="true"></i>
<i class="fa fa-trash fa-lg" style="color:red" aria-hidden="true"></i>
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
</div>
<div id="myEditModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabelEdit" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabelEdit">Edit Department</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<form class="form-horizontal" method="POST" action="{{ route('update_department', $departmentList->id) }}">
#csrf
#method('PUT')
<div class="form-group">
<div class="col-md-12">
<input type="text" name="nameOfDepartment" class="form-control" placeholder="Edit Department" value="{{$departmentList->nameOfDepartment}}">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info waves-effect" data-dismiss="modal">Update</button>
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
here is my code of department controller
<?php
namespace App\Http\Controllers;
use App\Department;
use Illuminate\Http\Request;
class DepartmentController extends Controller
{
public function createDepartment()
{
return view('pages.department');
}
public function storeDepartment(Request $request)
{
$department = new Department();
$department->createdBy = $request->get('createdBy');
$department->nameOfDepartment = $request->get('nameOfDepartment');
$department->save();
return redirect('list-department')->with('Success', 'Department Added Successfully!');
}
public function listDepartment()
{
$listOfDepartment = Department::all();
return view('pages.department', compact('listOfDepartment'));
}
public function editDepartment($id)
{
$departments = Department::find($id);
return view('pages.department', compact('departments', 'id'));
}
public function updateDepartment(Request $request, $id)
{
$department = Department::find($id);
$department->createdby = $request->get('createdBy');
$department->nameOfDepartment = $request->get('nameOfDepartment');
$department->save();
return redirect('list-department')->with('Success', 'Department Updated Successfully!');
}
public function deleteDepartment($id)
{
$department = Department::find($id);
$department->delete();
return redirect('list-department')->with('Success', 'Department Deleted SuccessFully!');
}
}
And Here Are My Routes
Route::get('add-department', 'DepartmentController#createDepartment')->name('create_department');
Route::post('store-department', 'DepartmentController#storeDepartment')->name('store_department');
Route::get('list-department', 'DepartmentController#listDepartment')->name('list_department');
Route::get('edit-department/{id}', 'DepartmentController#editDepartment')->name('edit_department');
Route::put('update-department/{id}', 'DepartmentController#updateDepartment')->name('update_department');
Route::get('delete-department/{id}', 'DepartmentController#deleteDepartment')->name('delete_department');
Your modal is always created with the last $departmentList
You are using this to create some kind of list
#foreach($listOfDepartment as $departmentList)
<tr>
<td>{{$departmentList->nameOfDepartment}}</td>
<td>{{$departmentList->createdBy}}</td>
<td>{{$departmentList->created_at}}</td>
<td>
<a href="{{route('edit_department', $departmentList->id)}}" data-toggle="modal" data-target="#myEditModal">
<i class="fa fa-edit fa-lg" style="color:#0066ff" aria-hidden="true"></i>
</a>
<a href="{{route('delete_department', $departmentList->id)}}">
<i class="fa fa-trash fa-lg" style="color:red" aria-hidden="true"></i>
</a>
</td>
</tr>
#endforeach
You end the loop here so $departmentList is the last one from the loop
Later you add some html again that uses $departmentList
<form class="form-horizontal" method="POST" action="{{ route('update_department', $departmentList->id) }}">
This variable still contains the last department from your loop before.
You can probably utilize some javascript that opens the modal and put the correct post url in place.

How get id from other user in Laravel

I am trying to create a user manager in Laravel, I have implemented methods for editing and deleting registered users in my database, but when I try to delete a selected user, it picks up the id of the logged in user, thus excluding the logged in user account.
Function Destroy from Admin Controller
public function destroy($id)
{
$user = User::find($id);
$user->delete($id);
}
View from Admin index
#extends('layouts.sidebar')
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="panel-heading">
<h2>Gerenciamento de usuários</h2>
<div class="panel-body">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertUser">
Adicionar Usuário
</button>
<!-- Modal -->
<div class="modal fade" id="insertUser" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Cadastro de usuários</h4>
</div>
<div class="modal-body">
<form class="" action="{{ url('/admin/criausuario')}}" method="post">
{{ csrf_field() }}
<label for="nome">Nome</label>
<input type="text" class="form-control" id="nome" placeholder="Nome Completo" name="nome"></br>
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email"></br>
<label for="senha">Senha</label>
<input type="password" class="form-control" id="senha" placeholder="Senha" name="senha"></br>
<label for="tipo">Tipo</label>
<select class="form-control">
<option value="0">Usuário</option>
<option value="1">Administrador</option>
</select>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
<button type="submit" class="btn btn-default">Cadastrar</button>
</div>
<div class="modal-footer">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<table class="table">
<tr>
<th>Avatar</th>
<th>ID</th>
<th>Nome</th>
<th>Email</th>
<th>Ações</th>
</tr>
<tr>
#foreach($users as $user)
<td> <img src="{{$user->avatar}}" alt="" style="width: 75px; border-radius: 50%;"> </td>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td><i class="glyphicon glyphicon-edit"></i>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#confirmacao">
<i class="glyphicon glyphicon-remove"></i>
</button></td>
</tr>
<div class="modal fade" id="confirmacao" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Confirmação</h4>
</div>
<div class="modal-body">
Você tem certeza que deseja excluir o usuário selecionado?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-danger">Excluir</button>
</div>
</div>
</div>
</div>
#endforeach
</table>
</div>
</div>
</div>
</div>
{{ $users->links()}}
#endsection
Route
Route::get('/admin', 'AdminController#index')->middleware('admin');
Route::get('/admin/editar/{id}', 'AdminController#edit')->middleware('admin');
Route::post('/admin/editar/{id}', 'AdminController#update')->middleware('admin');
Route::post('/admin/criausuario/', 'AdminController#store');
Route::get('/admin/deletar/{id}', 'AdminController#destroy')->name("user::deleteGet")->middleware('admin');
Any suggestion?

Resources