How I can display data using wheredoesnthave - laravel

I have one problem.i have group table
This table has many to many relationship with users table and I have declared the relationship in both model.
And this is join table
Group.php
class Group extends Model
{
use SoftDeletes;
use HasFactory;
public $timestamps=true;
protected $dates = ['deleted_at'];
public function creators()
{
return $this->belongsToMany(User::class);
}
}
User.php
class User extends Authenticatable
{
use SoftDeletes;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $dates = ['deleted_at'];
public function grp()
{
return $this->belongsToMany(Group::class);
}
}
This is the page where it will display the group that user have request
And supposedly in this page it will display the group that user have not request yet which is line no 3.
This is the code of my project.
Controller
public function redirectFunct(Request $request)
{
$role=Auth::user()->role;
$userid=Auth::user()->id;
if($role=='3')
{
$user = User::find(Auth::user()->id);
$groups=Group::with('creators');
$exists = Group::whereDoesntHave('creators', function ($query) {
$query->where('user_id', '=', Auth::user()->id);
})->get();
if($exists)
{
$users=Join::where('userID', '=', Auth::user()->id)->get();
}
$request = Join::where('userApprove','=','0')->where('userID',$userid)->get();
return view('member.dashboard',['users'=>$users,'user'=>$user,'groups'=>$groups,'exists'=>$exists,'request'=>$request]);
}
dasboard.blade.php
//sugessted group tab
<div class="tab-pane fade" id="sales" role="tabpanel" aria-labelledby="sales-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<li class="nav-item nav-search d-none d-lg-block w-100">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="search">
<i class="mdi mdi-magnify"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Search now" aria-label="search" aria-describedby="search">
</div>
</li>
<br>
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($exists as $group)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$group->groupName}}</td>
<td>{{$group->groupDesc}}</td>
<td>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModalCenter{{$group->id}}">Details</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter{{$group->id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Group Details</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Group Name:{{$group->groupName}}</p>
<p>Group Description : {{$group->groupDesc}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
<td><a href="{{url('/join',$group->id)}}"><button type="button" class="btn btn-secondary .btn-{color}">Join</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
//pending group tab
<div class="tab-pane fade" id="t" role="tabpanel" aria-labelledby="t-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($request as $req)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$req->group->groupName}}</td>
<td>{{$req->group->groupDesc}}</td>
<td><a href ="{{url('/cancelrequest',$req->id)}}"><button type="button" class="btn btn-danger .btn-{color}" onclick="return confirm('Are you sure?')">Cancel</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I really appreciated if someone help me, please inform if there is not enough information, I will add it ASAP.

Related

foreach showing two results in just one column - Laravel 9.x / Livewire

When I trigger foreach to show the products registered in each process, separated by line and column, it returns the result all in just one line.
Sorry about my English
Example:
ID
header 2
1525, 1523
Item 1, Item 2
what i want to show
ID
Name
1525
Item 1
1523
Item 2
Back End:
`
public function viewLicitacao($id) {
$licitacao = Licitacao::find($id); $this->showModalLicitacao();
$this->licitacao_id_processo = $licitacao->id;
$this->licitacao_destino = $licitacao->cliente_nome;
$this->licitacao_date_entrega = $licitacao->date_entrega;
}
Front End:
#if($isModal == true)
#foreach($licitacao as $processo)
<div class="modal fade" id="ModalLicitacao">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Licitação - {{ $processo->id; }}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h4>Informações das licitações</h4>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>N° do Processo: </label>
<input class="form-control" type="number" wire:model="licitacao_id_processo" placeholder="Informe o N° do processo" readonly/>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="destino">Destinatário: </label>
<input type="text" class="form-control" wire:model="licitacao_destino" placeholder="Informe o nome do destinatário" readonly/>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Data da entrega:</label>
<input type="text" wire:model="licitacao_date_entrega" class="form-control" placeholder="Data de entrega da mercadoria" readonly>
</div>
</div>
</div>
<h4>Produtos da licitação</h4>
<div class="row">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Preço Unit</th>
<th>Quantidade</th>
<th>Qt. Disponivel</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
#forelse($processo->products as $key => $products)
<td>{{ $products->id_product }}</td>
#empty
<td>Nenhum produto foi cadastrado nessa licitação</td>
#endforelse
</tbody>
</table>
</div>
</div>
<div class="modal-footer justify-content-between">
<button type="submit" wire:click="closeModalLicitacao()" class="btn btn-default">Fechar</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
#endforeach
<!-- /.modal -->
#endif
The two tables have relationships
Modal ProductLicitacao:
class ProductLicitacao extends Model
{
use HasFactory;
protected $fillable = [
'id_product', 'licitacao_id', 'name', 'qty', 'price_unit',
];
public function licitacao()
{
return $this->belongsTo(Licitacao::class);
}
}
Modal Licitacao:
class Licitacao extends Model
{
use HasFactory;
protected $fillable = [
'processo_number', 'cliente_nome', 'status', 'user_id', 'date_entrega', 'alert',
];
protected $dates = [
'date_entrega'
];
public function products()
{
return $this->hasMany(ProductLicitacao::class, 'licitacao_id');
}
}
Help me to solve this problem that seems to be simples, but it is being monstrous for my iniation in web development.
Try adding the tag <tr> before the <td>
<tbody>
#forelse($processo->products as $key => $products)
<tr>// <-- here
<td>{{ $products->id_product }}</td>
//other columns(td), you may have
</tr>// <-- and here
#empty
<td>Nenhum produto foi cadastrado nessa licitação</td>
#endforelse
</tbody>

Why Does Image Read Null When I Try To Delete My Category?

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush
I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

My LiveWIre wire Click Action is not working

This is my Livewire Component. When I try to click a function like delete it doesn't work and doesn't give me dd(). Everything is ok I've checked several times and tried everything.
#extends('admin.layouts.layout')
#section('content')
<!-- Modal -->
<div>
<div
class="modal fade"
id="deleteModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Catagory Delete</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<form wire:submit.prevent="destroyCatagory">
<div class="modal-body">
<h6>Are You Sure YOu Want To Delete this Data?</h6>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Close
</button>
<button type="submit" class="btn btn-primary">Yes Delete</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
#if (session()->has('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>
Catagory
<a
href="{{url('admin/catagory/create')}}"
class="float-end btn btn-primary"
>Add Catagory</a
>
</h4>
</div>
<div class="card-body">
<table class="table table-striped table-hover">
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
#forelse ($catagories as $catagory)
<tr>
<td>{{$catagory->id}}</td>
<td>{{$catagory->name}}</td>
<td>{{$catagory->status=='1'? 'Hidden':'visible'}}</td>
<td>
<a
href="{{url('admin/catagory/'.$catagory->id.'/edit')}}"
class="btn btn-success"
>
Edit</a
>
<a
wire:click="deleteCatagory({{$catagory->id}})"
class="btn btn-primary"
data-bs-toggle="modal"
data-bs-target="#deleteModal"
>Delete</a
>
</td>
</tr>
#empty #endforelse ($catagories as $catagory)
</table>
{{$catagories->links()}}
</div>
<div class="card-footer"></div>
</div>
</div>
</div>
</div>
#endsection
This is my index.blade.php for the livewire component. Everything seems to be ok in this component. I've checked everything several times and I've been stuck on this for many days, please help me.
public function deleteCatagory($id)
{
dd($id);
$this->catagory_id = $id;
}
public function destroycatagory()
{
$catagory= Catagory::find($this->catagory_id);
$path = 'uploads/catagory/'.$catagory->image;
if(File::exists($path)) {
File::delete($path);
}
$catagory->delete();
session()->flash('message','Catagory Deletd Successfully');
}

Problem with Laravel CRUD (Edit Function)

Good day everyone. I'm quite new to new to Laravel and was doing some basic CRUD coding, I was able to code the add and view function, but I'm having a hard time with the edit and delete function.
I have 4 files, the master blade file, the web.php (routing), the blade file and the Form Controller.
This is the promo.blade.php file:
<table class="table table-striped" id="table1" >
<thead>
<tr>
<th class="text-center">ACTION</th>
<th class="text-center">Offer ID</th>
<th class="text-center">Promo Name</th>
<th class="text-center">Promo Price</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
#foreach ($data as $key => $item)
<tr>
<td class="text-center">
<a href="#" data-bs-toggle="modal" data-bs-target="#show" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-success"><i class="bi bi-eye-fill"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#edit" data-mainid="{{$item->id}}" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-primary"><i class="bi bi-pencil-square"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#delete" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-danger"><i class="bi bi-trash"></i></span>
</a>
</td>
<td class="date text-center">{{ $item->offerId }}</td>
<td class="date text-center">{{ $item->promoName }}</td>
<td class="number text-center">{{ $item->promoPrice}}</td>
<td class="number text-center">{{ $item->isActive }}</td>
</tr>
#endforeach
</tbody>
</table>
<!--Start Modal Edit -->
<div class="modal fade text-left" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel160" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title white" id="add">
Edit Promo
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('promo.edit') }}" method="POST">
#csrf
<div class="form-group">
<label for="">ID</label>
<input type="text" class="form-control" name="id" id="id" value="">
<span style="color:red">#error('id'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Offer ID</label>
<input type="text" class="form-control" name="offerId" id="offerId" value="">
<span style="color:red">#error('offerId'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Name</label>
<input type="text" class="form-control" name="promoName" id="promoName" value="">
<span style="color:red">#error('promoName'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Price</label>
<input type="number" class="form-control" name="promoPrice" id="promoPrice" value="">
<span style="color:red">#error('promoPrice'){{$message}} #enderror</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">CANCEL</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">SAVE</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Modal Edit-->
Then this is the web.php file, for the routing:
Route::get('promo.promo', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.promo');
Route::post('promo.add', [App\Http\Controllers\FormControllerPromo::class, 'addPromo'])->name('promo.add');
Route::post('promo.delete/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDelete'])->middleware('auth');
Route::get('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.edit');
Route::get('promo.edit/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDetail'])->middleware('auth');
Route::post('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'edit'])->name('promo.edit');
This is the master.blade.php file:
<!--Start Modal edit for Promo-->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function (event){
var button = $(event.relatedTarget)
var mainid = button.data('mainid')
var id = button.data('myofferid')
var title = button.data('mytitle')
var price = button.data('myprice')
var modal = $(this)
modal.find('.modal-body #id').val(mainid);
modal.find('.modal-body #offerId').val(id);
modal.find('.modal-body #promoName').val(title);
modal.find('.modal-body #promoPrice').val(price);
})
</script>
<!--End Modal edit for Promo-->
I think this is the part where the code wont execute properly.
This is the FormControllerPromo.php file:
// view form
public function index()
{
return view('promo.promo');
}
// view record
public function viewRecord()
{
$data = DB::table('promo')->get();
return view('promo.promo',compact('data'));
}
// view detail
public function viewDetail($id)
{
$data = DB::table('promo')->where('id',$id)->get();
return view('promo.promo',compact('data'));
}
// edit promo
public function edit(Request $request){
$id = $request->input('id');
$offerId = $request->input('offerId');
$promoName = $request->input('promoName');
$promoPrice = $request->input('promoPrice');
DB::table('promo')
->where('id', $id) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('offerId' => $offerId, 'promoName' => $promoName, 'promoPrice' => $promoPrice)); // update the record in the DB.
$data = DB::table('promo');
return view('promo.promo',compact('data'));
}
I've been trying to code this for almost a week now with no success, any help is highly appreciated. :)
the update seems right, should work. but when you pass the $data variable to your view, you should call ->get(), because otherwise you return a query builder instance, that later raises the Undefined property error when trying to access {{$item->offerId}}.
change second last line in your example
//from this:
$data = DB::table('promo');
//to this:
$data = DB::table('promo')->get();
//or to this if you want to show only one record:
$data = DB::table('promo')->where('id', $id)->get();

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.

Resources