Laravel foreign key reference - laravel

I'm trying to reference the description of a foreign key via a relation, like follows:
My model.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Evento extends Model
{
//
protected $fillable = [
'idEvento',
'strNombreEvento',
'strDireccion',
'strCiudad',
'strCorreo',
'strTelefono',
'strEncargadoEvento',
'strNotas',
'idEscuela',
];
protected $primaryKey = 'idEvento';
public function escuela()
{
return $this->belongsTo('App\Escuela','idEscuela');
}
public function diaevento()
{
return $this->hasMany('App\diaEvento');
}
}
The relation
namespace App;
use Illuminate\Database\Eloquent\Model;
class Escuela extends Model
{
//
protected $fillable = [
'idEscuela',
'strNombreEscuela',
'bolPrincipal',
'strLogo',
'sitDiasUsuarioInactivo',
'sitDiasToleranciaCobro',
];
protected $primaryKey = 'idEscuela';
public function grupos()
{
return $this->hasMany('app\grupo');
}
public function eventos()
{
return $this->hasMany('app\eventos');
}
}
My view
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Eventos</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/eventos/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Evento</th>
<th>Escuela</th>
<th>Dirección</th>
<th>Ciudad</th>
<th>Correo</th>
<th>Teléfono</th>
<th>Contacto</th>
</tr>
</thead>
<tbody>
#foreach($eventos as $evento)
<tr>
<td> {{ $evento->strNombreEvento }} </td>
<td>{{ $evento->escuela->strNombreEscuela }}</td>
<td>{{ $evento->strDireccion }} </td>
<td>{{ $evento->strCiudad }} </td>
<td>{{ $evento->strCorreo }} </td>
<td>{{ $evento->strTelefono }} </td>
<td>{{ $evento->strEncargadoEvento }} </td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
My controller
public function index()
{
//
$eventos = evento::all();
return view('eventos.index', ['eventos'=>$eventos]);
}
The result.
The thing is that the same mechanics is working with another model, which I post:
namespace App;
use Illuminate\Database\Eloquent\Model;
class grupo extends Model
{
//
protected $fillable = [
'idGrupo',
'idEscuela',
'strNombreGrupo',
];
protected $primaryKey = 'idGrupo';
public function escuela()
{
return $this->belongsTo('App\Escuela','idEscuela');
}
public function horarioGrupo()
{
return $this->hasMany('App\horario_Periodicos');
}
}
The relation is the same as with evento above.
My view
#extends('layouts.app')
#section('content')
#guest
#else
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Grupos</a>
</nav>
<div class="container-fluid">
<div class="row">
<nav class="col-sm-1 d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<span data-feather="home"></span>
<span class="sr-only"></span>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/grupos/create">
<span data-feather="file"></span>
Nuevo
</a>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h5">Catálogo</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Exportar</button>
</div>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th>Nombre del grupo</th>
<th>Escuela</th>
</tr>
</thead>
<tbody>
#foreach($grupos as $grupo)
<tr>
<td> {{ $grupo->strNombreGrupo }} ></td>
<td>{{ $grupo->escuela->strNombreEscuela }}</td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
#endguest
#endsection
The controller
public function index()
{
//
$grupos = grupo::all();
return view('grupos.index', ['grupos'=>$grupos]);
}
I would appreciate your help.
Thanks.
I post my migrations, they where added today
The original Evento
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEventosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('eventos', function (Blueprint $table) {
$table->increments('idEvento');
$table->string('strNombreEvento', 200);
$table->string('strDireccion', 200);
$table->string('strCiudad', 200);
$table->string('strCorreo', 200);
$table->string('strTelefono', 20);
$table->string('strEncargadoEvento', 60);
$table->string('strNotas', 300);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('eventos');
}
}
These one was dump, thinking in a direct referent from the foreign table
From Evento to Escuela, no intermediate.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DeleteDiasEventoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::dropIfExists('dias_eventos');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::create('dias_eventos', function (Blueprint $table) {
$table->increments('idDiasEventos');
$table->integer('idEvento')->unsigned();
$table->foreign('idEvento')->references('idEvento')->on('eventos');
$table->integer('idDiaEventos')->unsigned();
$table->foreign('idDiaEventos')->references('id')->on('dia_eventos');
$table->unique(['idEvento','idDiaEventos']);
$table->timestamps();
});
}
}
Then I modified Evento, including the foreign key by itself.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ModifyEventoTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::table('eventos', function($table) {
$table->integer('idEscuela')->unsigned();
$table->foreign('idEscuela')->references('idEscuela')->on('escuelas');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('eventos', function (Blueprint $table) {
$table->dropForeign('eventos_idescuela_foreign');
$table->dropColumn('idEscuela');
});
}
}

Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

Related

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.

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

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 .

Sorting and searching a foreign entity field on a Laravel Livewire table

I’ve just implemented a Livewire data table based on the Caleb’s tutorial on Laracasts. Everything works as expected when working with just one model. However I’m stuck trying to apply sorting and searching to a foreign model field.
User model:
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user's email verified status.
*
* #param string $value
* #return string
*/
public function getEmailVerifiedAtAttribute($value)
{
if ($value == null) {
return "No";
}
return $value;
}
public function getRoleAttribute()
{
if($this->roles()->count() > 0) {
return $this->roles()->first()->name;
} else {
return "Usuario registrado";
}
}
public static function search($query)
{
return empty($query) ? static::query()
: static::where('name', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%');
}
}
Tried adding another orWhere() clause to the search() method in some ways. None worked. Now I left just the default ones.
Livewire controller:
namespace App\Http\Livewire\Users;
use Livewire\Component;
use Livewire\WithPagination;
class Table extends Component
{
use WithPagination;
public $perPage;
public $sortField;
public $sortAsc;
public $search;
public function mount()
{
$this->perPage = 10;
$this->sortField = 'name';
$this->sortAsc = true;
$this->search = '';
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
return view('livewire.users.table', [
'users' => \App\User::search($this->search)
->with('roles')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage),
]);
}
}
Livewire view:
<div>
<div class="row mb-4">
<div class="col form-inline">
Mostrar
<select wire:model="perPage" class="form-control form-control-sm custom-select custom-select-sm">
<option>10</option>
<option>100</option>
<option>1000</option>
</select>
registros
</div>
<div class="col-sm-3">
<input wire:model="search" class="form-control form-control-sm" type="text" placeholder="Buscar usuarios...">
</div>
</div>
<div class="table-responsive mb-4" >
<div class="table-header">
<table class="table table-sm text-nowrap" role="grid">
<thead>
<tr>
<th width="30%">
<a wire:click.prevent="sortBy('name')" role="button" href="#">
Nombre
#include('partials._sort-icon', ['field' => 'name'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('email')" role="button" href="#">
Correo electrónico
#include('partials._sort-icon', ['field' => 'email'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('')" role="button" href="#">
Rol
#include('partials._sort-icon', ['field' => ''])
</a>
</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table class="table table-sm table-hover text-nowrap" role="grid">
<tbody>
#foreach ($users as $user)
<tr>
<td width="30%">{{ $user->name }}</td>
<td width="30%">{{ $user->email }}</td>
<td width="30%">{{ $user->role }}</td>
<td>
<form method="POST" action="{!! route('backend.users.user.destroy', $user->id) !!}" accept-charset="UTF-8">
<input name="_method" value="DELETE" type="hidden">
{{ csrf_field() }}
<div class="btn-group btn-group-xs float-right" role="group">
#can('users.show')
<a href="{{ route('backend.users.user.show', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.show') }}">
<i class=" fas fa-fw fa-eye" aria-hidden="true"></i>
</a>
#endcan
#can('users.edit')
<a href="{{ route('backend.users.user.edit', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.edit') }}">
<i class=" fas fa-fw fa-pencil-alt" aria-hidden="true"></i>
</a>
#endcan
#can('users.destroy')
<button type="submit" class="btn btn-outline-default btn-xs" title="{{ trans('users.delete') }}" onclick="return confirm("{{ trans('users.confirm_delete') }}")">
<i class=" fas fa-fw fa-trash-alt" aria-hidden="true"></i>
</button>
#endcan
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="table-footer">
<div class="text-muted">
Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} out of {{ $users->total() }} results
</div>
<div>
{{ $users->links() }}
</div>
</div>
</div>
Tried also some ways to pass an argument to the sortBy() and [‘field’ => ‘’] on the role column. Now I left them with empty strings.
I know, this issue probably is more related to Laravel than Livewire, but I’ll really appreciate any help.
Update:
Solved using the Laravel Query Builder instead of Eloquent.

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