I deleted one of the data in the table based on id, but what was deleted was another id whose value is smaller - laravel

I have started learning Laravel framework since 2 weeks ago.
Here, I have 2 tables, namely anggotas and simpanans
which has one-to-many relationship,
one anggota (id_anggota as pk) can have many simpanan(id simpanan as pk).
I have used id_anggota as a foreign key in the simpanans table, but
when I delete one of the rows in the simpanans table based on id, it deletes another id whose value is smaller.
this is the models in Simpanan model
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Simpanan extends Model
{
use HasFactory;
// protected $table='simpanans';
protected $primaryKey = 'id_simpanan';
protected $keyType = 'string';
protected $fillable = [
'no_anggota','tgl','tabungan','s_wajib','s_thr','s_pendidikan','lain','catatan'
];
public function anggota(){
return $this->belongsTo(Anggota::class);
}
}
this is the models in Anggota model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Anggota extends Model
{
use HasFactory;
protected $primaryKey = 'id_anggota';
protected $keyType = 'string';
protected $fillable = [
'id_anggota','name','tmlahir','tglahir','alamat','ktp','pendidikan','pekerjaan','hp',
];
public function detailAnggota($id){
return DB::table('anggotas')->where('id_anggota', $id)->first();
}
public function simpanan(){
return $this->hasMany(Simpanan::class,'no_anggota','id_anggota');
}
}
this the controller
<?php
namespace App\Http\Controllers;
use App\Models\Simpanan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\Concerns\ManagesLayouts;
class SimpananController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('layouts.simpanan.simpanan');
}
public function __construct()
{
$this->Simpanan = new Simpanan();
}
public function simpan(){
$data=[
'simpanan'=>$this->Simpanan->joinAnggota()
];
return view('layouts.simpanan.simpanan',$data);
}
public function store(Request $request)
{
$rules=[
'id_anggota'=>'required',
'tglsetor'=>'required',
'tabungan'=>'required',
's_wajib'=>'required',
's_thr'=>'required',
's_pendidikan'=>'required',
'lain'=>'required',
'catatan'=>'nullable'
];
$messages = [
'tglsetor.required'=> 'Tanggal harus diisi!!!',
'tabungan.required'=> 'Tabungan harus diisi dengan angka, atau diisi dengan angka 0 !!!',
's_wajib.required'=> 'Simpanan Wajib harus diisi dengan angka, atau diisi dengan angka 0 !!!',
's_thr.required'=> 'Simpanan THR harus diisi dengan angka, atau diisi dengan angka 0 !!!',
's_pendidikan.required'=> 'Simpanan Pendidikan harus diisi dengan angka, atau diisi dengan angka 0 !!!',
'lain.required'=> 'Dana Lain harus diisi dengan angka, atau diisi dengan angka 0 !!!',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput($request->all());
}
$simpan = new Simpanan();
$simpan->anggota_id_anggota = $request->id_anggota;
$simpan->tgl = $request->tglsetor;
$simpan->tabungan = $request->tabungan;
$simpan->s_wajib = $request->s_wajib;
$simpan->s_thr = $request->s_thr;
$simpan->s_pendidikan = $request->s_pendidikan;
$simpan->lain = $request->lain;
$simpan->catatan = $request->catatan;
$simpan->save();
return redirect('/simpanan')->with('status','Data berhasil ditambahkan');
}
public function edit($id)
{
$simpanan=Simpanan::find($id);
return view('layouts.simpanan.edit',['simpanan'=>$simpanan]);
}
public function update(Request $request, $id)
{
$simpanan=Simpanan::find($id);
$simpanan->update([
'tgl'=>$request->tglsetor,
'tabungan'=>$request->tabungan,
's_wajib'=>$request->s_wajib,
's_thr'=>$request->s_thr,
's_pendidikan'=>$request->s_pendidikan,
'lain'=>$request->lain,
'catatan'=>$request->catatan
]);
return redirect('/simpanan')->with('status','Data Berhasil Dirubah');
}
public function destroy($id)
{
$simpanan=Simpanan::findOrFail($id)->where('id_simpanan',$id);
$simpanan->delete();
return redirect('/simpanan')->with('status','Data Berhasil Dihapus');
}
}
and this the view
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">History Simpanan</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">No.</th>
<th scope="col">ID Transaksi</th>
<th scope="col">Tanggal</th>
<th scope="col">Nomor Anggota</th>
<th scope="col">Nama</th>
<th scope="col">Tabungan</th>
<th scope="col">S. Wajib</th>
<th scope="col">S. THR</th>
<th scope="col">S. Pendidikan</th>
<th scope="col">Aksi</th>
</tr>
</thead>
#php $no=1; #endphp
#foreach ($simpanan as $data)
<tbody>
<tr>
<td>{{$no++}}</td>
<td>STR{{$data->id_simpanan}}</td>
<td>{{$data->tgl}}</td>
<td>{{$data->id_anggota}}</td>
<td>{{$data->name}}</td>
<td>{{$data->tabungan}}</td>
<td>{{$data->s_wajib}}</td>
<td>{{$data->s_thr}}</td>
<td><span class="badge bg-danger">{{$data->s_pendidikan}}</span></td>
<td>
<div class="text-right">
<a href="/simpanan/edit/{{$data->id_simpanan}}" class="btn btn-sm btn-success">
<i class="fas fa-user"></i> Edit
</a>
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#modal-sm">
<i class="fas fa-user"></i> Hapus
</button>
</div>
</tr>
</tbody>
#endforeach
</table>
</div>
<!-- /.card-body -->
<div class="modal fade" id="modal-sm">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Yakin hapus data?</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Data yang dihapus tidak dapat kembali…</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<a href="/simpanan/hapus/{{$data->id_simpanan}}" methode="post" class="btn btn-sm btn-danger">
<i class="fas fa-user"></i> Hapus
</a>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="d-flex justify-content-center">{{$simpanan->links()}}</div>
</div>
<!-- /.card -->
<!-- /.col -->
</div>
<!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->

In the table you can add an event listener to listen for click on the button like this to call a JavaScript function that gets the ID:
<td>
<div class="text-right">
<a
href="/simpanan/edit/{{$data->id_simpanan}}"
class="btn btn-sm btn-success"
>
<i class="fas fa-user"></i> Edit
</a>
<button
type="button"
class="btn btn-sm btn-danger"
data-toggle="modal"
data-target="#modal-sm"
onclick="pass_id_to_modal({{ $data->id }})"
>
<i class="fas fa-user"></i> Hapus
</button>
</div>
</td>
Also, for the modal, we can set "#" for href because we are going to set it dynamically, instead we can add a ID for the button to be accessible via the JavaScript function like this:
<!-- modal -->
<div class="modal fade" id="modal-sm">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Yakin hapus data?</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Data yang dihapus tidak dapat kembali…</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<a id="modal_delete_link" href="#" methode="post" class="btn btn-sm btn-danger">
<i class="fas fa-user"></i> Hapus
</a>
</div>
</div>
</div>
</div>
Now, you can either create a JS file or add the following function inside the View itself to handle the ID transfer the modal:
function pass_id_to_modal(id) {
var delete_button = document.getElementById("modal_delete_link");
delete_button.href = "/simpanan/hapus/" + id;
}

try this
$simpanan=Simpanan::where('id_simpanan',$id);
$simpanan->delete();
the above code will delete all simpanan with given id .
$simpanan=Simpanan::find($id)->delete();
the above code will delete one row matched with given id .

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}})"

How I can display data using wheredoesnthave

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.

How to fetch user's profile info related to user using laravel?

I want to fetch user's profile info related to user and i have already made relationship b/w user and profile one to one relation but I don't know how to fetch this?
Does anybody have an idea please help me thanks
Database table
Profile table has User_name,phone_number,Job ,user_id
controller
public function viewprofile()
{
return view('viewprofile');
}
profile model
class Profile extends Model
{
protected $table = 'Profiles';
protected $fillable = ['User_name', 'phone_number', 'Job'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
class User extends Authenticatable
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
profile view
<div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
<div class="card bg-light">
<div class="card-header text-muted border-bottom-0">
Digital Strategist
</div>
<div class="card-body pt-0">
<div class="row">
<div class="col-7">
<h2 class="lead"><b>Name: Your Name</b></h2>
<p class="text-muted text-sm"><b>Job: </b> Web Designer / UX / Graphic Artist /
Coffee Lover </p>
<ul class="ml-4 mb-0 fa-ul text-muted">
<li class="small"><span class="fa-li"><i class="fas fa-lg fa-phone"></i></span>
Phone
#: + 800 - 12 12 23 52
</li>
</ul>
</div>
<div class="col-5 text-center">
<img src="../../dist/img/user1-128x128.jpg" alt="" class="img-circle img-fluid">
</div>
</div>
</div>
<div class="card-footer">
<div class="text-right">
<a href="#" class="btn btn-sm bg-teal">
<i class="fas fa-comments"></i>
</a>
<a href="#" class="btn btn-sm btn-primary">
<i class="fas fa-user"></i> View Profile
</a>
</div>
</div>
</div>
</div>
The users profile will be accessible through the relationship and you can get access to it by calling the relationship as a property:
$profile = auth()->user()->profile;
If you need to be able to display it in your view, then just pass it through:
public function viewprofile()
{
return view('viewprofile', ['profile' => auth()->user()->profile]);
}

Trying to get property 'nom_matiere' of non-object laravel shows me this error

i want to display the name of matiere in this page but he shows me this error Trying to get property 'nom_matiere' of non-object
i make a selection in the note page to select the matiere then give a note to here it work but when i display the name of matiere in my table it give me error
model note
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
protected $fillable = ['note'];
public function matieres()
{
return $this->belongsToMany(Matiere::class);
}
}
model matiere
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Matiere extends Model
{
protected $fillable = ['nom_matiere','coef'];
public function notes() {
return $this->belongsToMany(Note::class);
}
}
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;
class NoteController extends Controller
{
public function index()
{
$notes = Note::paginate(5);
$matieres = Matiere::all();
return view('admin.notes',compact('notes','matieres'));
}
public function store(Request $request)
{
Note::create($request->all());
session()->flash('success',' cette note a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
session()->flash('success','cette note a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$note = Note::findOrFail($request->note_id);
$note->delete();
session()->flash('success','cette note a été supprimé avec succés');
return redirect()->back();
}
}
my view
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-note</th>
<th>La note</th>
<th>nom matiere</th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note)
<tr>
<td class="numeric" data-title="id-note" >{{$note->id}}</td>
<td class="numeric" data-title="Nom">{{$note->note}}</td>
<td class="numeric" data-title="Nom">{{$note->matiere->nom_matiere}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "data-mynote="{{$note->note}}" "data-mymatiere="{{$note->nom_matiere}}" data-catid={{$note->id}} class="edit" data-toggle="modal" ><i class="material-icons" data-toggle="tooltip" title="Edit"></i> </button>
<button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal" data-catid={{$note->id}} class="delete" data-toggle="modal" > <i class="material-icons" data-toggle="tooltip" title="Delete"></i> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
{{ $notes->links() }}
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('notes.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter note</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>La note</label>
<input type="text" id="note" name="note" class="form-control" required>
</div>
</div>
<div class="form-group select">
<select name="matiere_id">
<option value="">--selectionner la mtiére svp --</option>
#foreach($matieres as $matiere)
<option value="{{ $matiere->id }}">{{ $matiere->nom_matiere }}</option>
#endforeach
</select>
</select>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
You're calling $note->matiere in your view but the relationship is called matieres, which would be a collection.
Instead of:
<td class="numeric" data-title="Nom">{{ $note->matiere->nom_matiere }}</td>
You'd need:
<td class="numeric" data-title="Nom">
#foreach ($note->matieres as $matiere)
{{ $matiere->nom_matiere }}
#endforeach
</td>
I do however suspect that you have set your relationship up wrong. You've got the Note -> Matiere relationship set to belongsToMany, which means that you need a pivot table to contain the FK relationships. This would only be used if your Note is the child of many Matiere.
It does sound like you have your relationships set up wrong, but without really understanding what you're trying to do it's hard to tell you what exactly needs to be done.
Separate issue, but in your class update() method you've also got:
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
This means that you actually update the Matiere model no the Note model.

Resources