cant display all result from 2 table join with pivot table - php

I have managed to join between 2 tables by using 1 pivot table(I have to), but I cant loop my way to get all of joined result, Bellow are:
Models
App.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class App extends Model
{
protected $table = 'bas_app';
public $timestamps = false;
protected $fillable = ['id','app_name','app_type','description','menu_name','menu_url','menu_parent_id'];
public function roles()
{
return $this->belongsToMany(Role::class,'bas_role_app','app_id','role_id');
}
}
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//
protected $table = 'bas_role';
protected $fillable = ['name','remark'];
public function users()
{
return $this->belongsToMany('App\User','bas_user_role','role_id','user_id')
->withPivot('id');
}
public function apps()
{
// return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id')
// ->withPivot('id','priv_access','priv_insert','priv_delete',
// 'priv_update','priv_export','priv_print','app_name');
return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id');
}
}
RoleApp.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleApp extends Pivot
{
//
public $timestamps = false;
protected $table = 'bas_role_app';
protected $fillable = ['role_id','app_id','app_name'];
public function b_app() {
return $this->belongsToMany(App::class);
}
public function b_role() {
return $this->belongsToMany(Role::class);
}
}
Controller
RoleAppController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Route;
use App\User;
use App\Role;
use App\App;
use App\ActivityLog;
use App\RoleApp;
use Illuminate\Support\Facades\Input;
use DB;
class RoleAppController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function display(Request $request)
{
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
DB::beginTransaction();
try {
$id = Auth::id();
$profile_data = User::find($id);
$RoleApp = Role::all();
//$RoleApp->apps;
// dd($RoleApp);
ActivityLog::create([
'inserted_date' => Carbon::now()->TimeZone('asia/jakarta'),
'username' => $profile_data->username,
'application' => $routes,
'creator' => "System",
'ip_user' => $request->ip(),
'action' => $action,
'description' => "admin is looking at the role and application management",
'user_agent' => $request->server('HTTP_USER_AGENT')
]);
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
// return view('RoleApp', ['RoleApp' => $RoleApp]);
return view('RoleApp', ['RoleApp' => $RoleApp]);
} else {
return view("login");
}
}
}
View
RoleApp.blade.php
#extends('layouts.master')
#section('title','Display-RoleApp')
#section('content')
<div class="container mt-5">
<div class="row">
<div class="col-12">
#if($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ implode(', ', $errors->all(':message')) }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="float-right mb-5">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Insert Role App
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" 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">Insert User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/roleapp/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="role_name">role name:</label>
<input type="text" class="form-control" name="role_name">
</div>
<div class="form-group">
<label for="app_name">app name:</label>
<input type="text" class="form-control" name="app_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<div class="table-responsive m-b-40">
<table id="roleapp-table" class="table table-striped">
<thead>
<tr>
<th scope="col">Role Name</th>
<th scope="col">App Name</th>
<th scope="col" class="text-center">Action</th>
<th scope="col" class="text-center">Action</th>
</tr>
</thead>
<tbody id="dynamic-row">
#foreach ($RoleApp->apps as $rp)
<tr>
<td>{{$RoleApp->name}}</td>
<td>{{$rp->app_name}}</td>
<td class="text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
</td>
<td class="text-center">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
var row = 0;
$(document).ready(function() {
$('#user-table').DataTable({
select: true,
retrieve: true,
"order": [
[0, "desc"]
],
"lengthMenu": [
[20, 50, 100, 500, 1000, -1],
[20, 50, 100, 500, 1000, "All"]
],
"language": {
"paginate": {
"next": ">",
"previous": "<"
}
}
});
});
$('#user-table thead tr').clone(true).appendTo('#user-table thead');
$('#user-table thead tr:eq(1) th').each(function(i) {
if (row < 7) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
} else {
$(this).html('');
}
row++;
$('input', this).on('keyup change', function() {
if (table.column(i).search() !== this.value) {
table
.column(i)
.search(this.value)
.draw();
}
});
});
</script>
#endsection
Any suggestion? I have tried various way and its still not working. I suspect that something is wrong in
$RoleApp = Role::all();
or
#foreach ($RoleApp->apps as $rp)
<tr>
<td>{{$RoleApp->name}}</td>
<td>{{$rp->app_name}}</td>
<td class="text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
</td>
<td class="text-center">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
</td>
</tr>
#endforeach
if I try it with $RoleApp = Role::find(2); it will still work, but when i use get or all, it wont work.

without eager loading.
$roles = Role::all();
with eager loading
$roles = Role::with('apps')->get();
$roles is a collection of model instances of Role Model. You can't access a property or relation of a model, on a collection. That is the reason it works when you use find(given model instance), and doesn't work for all or get(give collection).
You need to iterate over the collection and then access the relation like this.
foreach($roles as $role){
// name of each role.
$role->name;
foreach($role->apps as $app){
// name of each app associated with the $role.
$app->name;
}
}

Related

How to show the checkbox data using modal bootstrap

i have created the form normally, but after I want to parse the data into index, there is data is not showed normally..
This a code for model Form
protected $guarded = [];
public function user(){
return $this->hasOne('App\User', 'id', 'user_id'); //Product Model Name
}
public function location(){
return $this->hasOne('App\Locations', 'id', 'location_id');
}
public function purpose(){
return $this->hasOne('App\Purpose', 'id', 'purpose_id');
}
public function connection(){
return $this->hasMany('App\FormConnection', 'id', 'form_connection'); //Product Model Name
}
This a code for model FormConnection
public function form(){
return $this->belongsTo('App\Form', 'id', 'form_id'); //Product Model Name
}
This is for Views of Modal
<div class="modal fade" id="exampleModal{{$form->id}}" 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">Form Information</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p class="badge badge-pill badge-dark">Name: {{$form->user->name}}</p>
<p>Purpose : {{$form->purpose->name}}</p>
<p>Location : {{$form->location->location}}</p>
<!-- <table class="table">
<tbody>
<tr>
<th scope="row">Connection</th>
<td><input type="checkbox" name="connection[]" value="request">Request</td>
<td><input type="checkbox" name="connection[]" value="connection">Connection</td>
</tr>
</tbody>
</table> -->
#foreach()
<div class="col-md-6 mt-2">
<label for="">waw</label>
</div>
#endforeach
<p>Division : {{$form->division}}</p>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I Hope someone can help me, I really appreciate that:))
output: The connection should show all connection that has been checked before
enter image description here

Slow simple eloquent queries

Im new to laravel eloquent and i want to know if that loading times are normally with only five entries
Even a simple select all query has ~720 ms specially on edit button that is first photo (modal) the data comes after one second that is noticeable,
Im using Livewire i dont know if affect that too much
The main question that affects extra loading time is how to have access (Aggregate) on child table that counts only the sum of the services, i wrote a simple count on my html {{ $customer->services->count()}} table as you can see runs on each row that is wrong because adds extra loading time.
On php i make something like :
$sql = "SELECT name,vat,id";
$sql .= " ,(select sum(taskcharges) from charges where charges.customers_id=customers.id) as taskcharges_sum";
$sql .= " ,(select sum(payment) from charges where charges.customers_id=customers.id) as payment_sum";
$sql .= " ,(select sum(taskcharges-payment) from charges where charges.customers_id=customers.id) as balance_sum";
$sql .= " ,(select name WHERE customers.id=$id) ";
$sql .= " FROM customers ";
I want to have access from Customers on specific child(services) columns to make functions like max,sum,count the tables are binded on model so i want to avoid extra code of join queries
plus as you can see on sorting the "services" isnt column of Customers table so they dont recognize the column services on customers table, if i had something like "select count(services) as servicecount then i will able to recognize the sorting as new column of the table customers
Above you can see my code:
customers/show.blade.php:
<div class="container">
<p>Sort column:{{$selectedItems}}</p>
<p>Selected Direction:{{$action}}</p>
<!-- Button trigger modal -->
<button wire:click.prevent="addNew" type="button" class="btn btn-primary">
Add New User
</button>
<!-- button triger Modal -->
<div class="modal fade" id="form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Insert</h5>
<button type="button" wire:click.prevent="close"class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#livewire('customers.form')
</div>
</div>
</div>
</div>
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="delete" aria-hidden="true" wire:ignore>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delete">Delete</h5>
<button type="button" wire:click.prevent="close" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h3>Do you wish to continue?</h3>
</div>
<div class="modal-footer">
<button type="button" wire:click="close" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button wire:click="delete" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
<h1 class="text-center">Customers {{count($customers)}}</h1>
<div>
<div class="w-full flex pb-10">
<div class="w-3/3 mx-1">
<input wire:model.debounce.300ms="search" type="text" class="form-control" placeholder="Search users...">
</div>
<div class="row mb-4">
<div class="col form-inline">
Per Page:
<select wire:model="perPage" class="form-control">
<option>5</option>
<option>10</option>
</select>
</div>
</div>
</div>
<table class="table-auto w-full mb-6">
<thead>
<tr>
<th wire:click="sortBy('id')" style="cursor: pointer;" class="px-4 py-2">ID
#include('layouts.partials.sort_icons',['field'=>'id'])
</th>
<th wire:click="sortBy('name')" style="cursor: pointer;" class="px-4 py-2">Name
#include('layouts.partials.sort_icons',['field'=>'id'])</th>
<th wire:click="sortBy('plate')" style="cursor: pointer;" class="px-4 py-2">Plate
#include('layouts.partials.sort_icons',['field'=>'id'])</th>
<th wire:click="sortBy('services')" style="cursor: pointer;" class="px-4 py-2">Services
#include('layouts.partials.sort_icons',['field'=>'services'])</th>
<th class="px-2 py-2">Action</th>
</tr>
</thead>
<tbody>
#foreach($customers as $customer)
<tr>
<td class="border px-4 py-2">{{ $customer->id }}</td>
<td class="border px-4 py-2">{{ $customer->name }}</td>
<td class="border px-4 py-2">{{ $customer->plate }}</td>
<td class="border px-4 py-2">{{ $customer->services->count()}}</td>
<td class="border px-2 py-2">
<button wire:click="selectItem({{$customer->id}},'update')" class="btn btn-info"><i class="fa fa-edit"></I></button></a>
<button wire:click="selectItem({{$customer->id}},'delete')" class="btn btn-danger"><i class="fa fa-trash"></I></button></a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="paginate">{{$customers->links()}}</div>
</div>
</div>
customers/Show.php :
<?php
namespace App\Http\Livewire\Customers;
use App\Models\Customer;
use Livewire\Component;
use App\Page;
use Illuminate\Support\Str;
use App\Http\Livewire\Column;
use Livewire\WithPagination;
class Show extends Component
{
public $sortBy= 'name';
public $sortDirection = 'asc';
public $headers;
public $perPage ='5';
public $search;
public $action;
public $selectedItems;
public function sortBy($field){
if ($this->sortDirection =='asc'){
$this ->sortDirection ='desc';
}
else{
$this->sortDirection ='asc';
}
return $this ->sortBy = $field;
}
public function selectItem($itemId,$action){
$this->selectedItems=$itemId;
$this->action=$action;
if ($action=='delete'){
$this->dispatchBrowserEvent('show-deletemodal');
} else{
$this->emit('getcustomerID', $this->selectedItems);
$this->dispatchBrowserEvent('show-modal');
}
}
public function delete(){
Customer::destroy($this->selectedItems);
$this->dispatchBrowserEvent('hide-modal');
}
public function addNew()
{
$this->dispatchBrowserEvent('show-modal');
}
public function close()
{
$this->dispatchBrowserEvent('hide-modal');
}
protected $listeners = [
'deleteconfirmed'=>'$selectedItems',
'refreshParent'=>'$refresh'
];
public function render()
{
$customers = Customer::query()
->search($this->search)
->orderBy($this->sortBy,$this->sortDirection)
->paginate($this->perPage);
return view('livewire.customers.show',['customers'=>$customers
])
->extends('admin.dashboard')
->section('content');
}
}
customers/form.php :
<?php
namespace App\Http\Livewire\Customers;
use App\Models\Customer;
use Livewire\Component;
class Form extends Component
{
public $name ='';
public $plate = '';
public $customerId ;
protected $listeners = [
'getcustomerID'
];
protected function rules() {
return [
'name' => 'required',
'plate' => ['required', 'regex:/[A-Z]{3}\d{4}$/','unique:customers,plate,' . $this->customerId],
];
}
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function getcustomerID($customerId){
$this->customerId=$customerId;
$customer= customer::find ($this->customerId);
$this->name=$customer->name;
$this->plate= $customer->plate;
}
public function save()
{
$this->validate();
$data = [
'name' => $this->name,
'plate' => $this->plate,
];
if ($this->customerId){
customer::find ($this->customerId)->update($data);
session()->flash('message', 'User successfully updated.');
} else{
customer::create($data);
}
$this->emit('refreshParent');
$this->dispatchBrowserEvent('hide-modal');
$this ->ClearVars();
}
public function ClearVars(){
$this->name=null;
$this->plate=null;
}
public function render()
{
return view('livewire.customers.form');
}
}
Models/Customer.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use HasFactory;
protected $fillable = [
'name',
'plate'
];
public function services()
{
return $this->hasMany(Service::class);
}
public function parts()
{
return $this->hasMany(Part::class, 'customer_id');
}
public function scopeSearch($query , $val){
return $query
->where('name','like','%'.$val.'%')
->Orwhere('plate','like','%'.$val.'%');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Models/Services.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Service extends Model
{
protected $fillable = [
'service_type',
'km',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function parts()
{
return $this->hasMany(part::class);
}
}
It was so simple.. just added ->withCount('services') above of query
Still have that strange delay
Update :
The problem with slow response was that trying to retrieve data from remote sql server, I change to local and I have less than 100ms!

Alias column name in view laravel

Hi so I have a 3 join table that naturally will have duplicate column name, for example, id. So in short, I have 3 table, which are:
bas_role
id
name
bas_app
id
app_name
bas_role_app
id
role_id
app_id
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Route;
use App\User;
use App\Role;
use App\App;
use App\ActivityLog;
use App\RoleApp;
use DataTables;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\JsonEncodingException;
use DB;
class RoleAppController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function display(Request $request)
{
// $role = \App\Role::first();
// $app = \App\App::first();
// // $role->apps()->attach($app);
// $app->roles()->attach($role);
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
$id = Auth::id();
DB::beginTransaction();
try {
$profile_data = User::find($id);
ActivityLog::create([
'inserted_date' => Carbon::now()->TimeZone('asia/jakarta'),
'username' => $profile_data->username,
'application' =>$routes,
'creator' => "System",
'ip_user' => $request->ip(),
'action' => $action,
'description' => $profile_data->username. " is looking at roleApp",
'user_agent' => $request->server('HTTP_USER_AGENT')
]);
// $pagination = TRUE;
$app =DB::table('bas_role_app')
->join('bas_role_app','bas_app.id','=','bas_role_app.app_id')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
// ->where('role_user.role_id', 4)
->select('*')
// ->from('bas_app')
// // ->where('role_user.role_id', 4)
->Orderby('bas_role_app.id')
->get();
// dd($app);
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
// dd($app);
return view('/roleapp', ['app' => $app]);
}else {
return view("login");
}
}
public function getroleapp(){
$app = DB::table('bas_role_app')
->join('bas_role_app','bas_app.id','=','bas_role_app.app_id')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->select('*')
->get();
return Datatables::of($app)->make(true);
}
public function update(Request $req, $id)
{
// if(request()->ajax())
// {
// $data = DB::table('bas_role_app')->findOrFail($id);
// return response()->json(['result' => $data]);
// }
}
public function delete(Request $request, $id)
{
try {
$role = RoleApp::findOrFail($id);
// // $app->roles()->detach();
$role->apps()->detach();
// // $app->delete();
$role->delete();
// $app_id = (int)Request('visit_id');
// $role_id = (int)Request('product_id');
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
return redirect('/roleapp');
}
public function insert(Request $request)
{
}
public function descriptionLog($id, $temp, $oldData, $newData)
{
$newString = '<div><table class="table table-striped"><tr><td scope="col"><b>ID:</b> </td><td><b>' . $id . '</b></td><td></td></tr><tr><td><b>Field</b></td><td><b>Old Data</b></td><td><b>New Data</b></td></tr>';
$arr = '';
for ($k = 0; $k < count($oldData); $k++) {
if ($oldData[$k] != $newData[$k]) {
$arr = '<tr><td>' . $temp[$k] . '</td><td>' . $oldData[$k] . '</td><td>' . $newData[$k] . '</td></tr>';
}
}
$newString = $newString . $arr . '</table></div>';
return $newString;
}
}
My View
#extends('layouts.master')
#section('title','App')
#section('content')
<div class="container mt-5">
<div class="row">
<div class="col-12">
<!-- Modal -->
<div class="float-left">
<div class="form-group mx-sm-3 mb-2">
<form class="form-inline">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#exampleModalCenter">
<i class="ni ni-fat-add"></i>
</button>
</div>
</form>
</div>
{{-- <div class="modal fade" id="exampleModalCenter" 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">New Role App</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="roleapp/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="username">Role Name</label>
<input type="text" class="form-control" name="app_name" required>
</div>
<div class="form-group">
<label for="Type">App Name</label>
<input type="text" class="form-control" name="app_type" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<button type="submit" class="btn btn-primary"><i class="ni ni-check-bold"></i></button>
</div>
</form>
</div>
</div>
</div> --}}
<table class="table table-striped" id="app">
<thead>
<tr>
<th scope="col">Role Name</th>
<th scope="col">App Name</th>
<th scope="col">Action</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="dynamic-row">
</tbody>
</table>
{{-- #foreach ($app as $p)
<div class="modal fade" id="modal_edit_{{$p->id}}" tabindex="-1" role="dialog" 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">Edit App</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="app_form_{{$p->id}}" action="{{ url('update', [$p->id]) }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" form="app_form_{{$p->id}}" />
<div class="form-group">
<label for="username">Name App</label>
<input type="text" class="form-control" name="app_name" value="{{$p->app_name}}">
</div>
<div class="form-group">
<label for="Type">Type App</label>
<input type="text" class="form-control" name="app_type" value="{{$p->app_type}}">
</div>
<div class="form-group">
<label for="name">Description</label>
<input type="text" class="form-control" name="description" value="{{$p->description}}">
</div>
<div class="form-group">
<label for="text">Nama Menu</label>
<input type="text" class="form-control" name="menu_name" value="{{$p->menu_name}}">
</div>
<div class="form-group">
<label for="phone">URL Menu</label>
<input type="text" class="form-control" name="menu_url" value="{{$p->menu_url}}">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<button type="submit" form="app_form_{{$p->id}}" class="btn btn-primary"><i class="ni ni-check-bold"></i></button>
</div>
</form>
</div>
</div>
</div>
#endforeach --}}
#foreach ($app as $p)
<div class="modal fade" id="modal_hapus_{{$p->id}}" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Data akan dihapus</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Data yang dihapus tidak dapat dikembalikan!
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="ni ni-fat-remove"></i></button>
<i class="ni ni-check-bold"></i>
</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
<link rel="stylesheet" href="{{ asset('css/breadcrumb.css') }}">
<script>
//load search, individual or not
var row = 0;
$(document).ready(function() {
$('#app thead tr').clone(true).appendTo( '#app thead' );
$('#app thead tr:eq(1) th').each( function (i) {
if (row < 2) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
} else {
$(this).html('');
}
row++;
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
//load datatable processing, using serverside yajra, with pagination option, also action button as well
var table = $('#app').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getroleapp') }}",
"lengthMenu" : [[20, 50, 100, 500, 1000, -1],[20, 50, 100, 500, 1000, "All"]],
"columns":[
{ "data": "name" },
{ "data": "app_name" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_edit_'+full.id+'"><i class="ni ni-single-02"></i></button>';
}
},
{
sortable: false,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_'+full.id+'"><i class="ni ni-fat-delete"></i></button>';
}
},
],
});
} );
</script>
#endsection
Here is the catch, I want to load the column id of bas_role_app, so I can do crud more easily. But when I do dd($app);, it always return the result with, for example, this:
+"id": 4
+"app_name": "app"
+"app_type": null
+"description": "display app"
+"menu_name": "app"
+"menu_url": "/app"
+"menu_parent_id": null
+"role_id": 4
+"app_id": 7
+"priv_access": "N"
+"priv_insert": "N"
+"priv_delete": "N"
+"priv_update": "N"
+"priv_export": "N"
+"priv_print": "N"
+"name": "siswa"
+"remark": "study"
from this, I know that the query load the wrong id for process, because in bas_role_app, it has reached about 1100 id(dummy data happens....)
So my question is, how do I load the id of bas_role_app so I can use it on view foreach loop(instead of the id of bas_role and bas_app) and I can do crud as well?
Try doing a column alias in your select for the id column you want to select as following:
$app = DB::table('bas_role_app')
->join('bas_role_app','bas_app.id','=','bas_role_app.app_id')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->select('bas_app.*,bas_role_app.id as bas_role_app_id')
Nevermind, apparently, I have to add the same query with method display and getroleapp, I should have been more careful

How to display parent name in Laravel

I have a departments table in db with id,name, and parent.The parent is the id that corresponds to the parent root.Now i have displayed the id(parent id) but i want to show the name of the department that correspond with this id.I have tried the query at the departmentcontroller ,index function but it gives me this error
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'departments' (SQL: select departments.id, departments.parent, departments.name from departments inner join departments on department.id = departments.parent where id = parent)
DepartmentController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Department;
use App\User;
use Illuminate\Support\Facades\DB;
class DepartmentController extends Controller
{
public function usersdep($id)
{
$department = Department::with('users')->find($id);
return view('admin.page-users')->with('users', $department->users);
}
public function treeView()
{
$departments = Department::with('childs')->where('parent', 0)->get();
return view('admin.page',compact('departments'));
}
public function index()
{
//$departments = \App\Department::all();
//return view('admin.department')->with('departments', $departments);
return $departments = DB::table('departments')
->join('departments', 'department.id', '=', 'departments.parent')
->select('departments.id','departments.parent','departments.name')->where('id','=','parent')->get();
}
department.blade.php
#extends ('layouts.master')
#section('title')
Department Management | Admin
#endsection
#section('content')
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
<form action="/save-department" method="POST">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Name</label>
<input type="text" class="form-control" name="name" id="recipient-name">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">ID</label>
<input type="text" class="form-control" name="id" id="recipient-id">
</div>
<div class="form-group">
<label for="recipient-name exampleFormControlSelect2" class="col-form-label">Parent ID</label>
<input type="text" class="form-control" placeholder="Choose the department parent id"name="parent" id="recipient-parent">
<select multiple class="form-control" name="parent" id="recipient-parent">
#foreach($departments as $department)
<option>{{ $department->parent }}</option>
#endforeach
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="card-header">
<h4 class="card-title my-4 text-center font-weight-light"> Department Management </h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<th>Department</th>
<button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#exampleModal" >Add</button>
<thead class=" text-primary">
<th>ID</th>
<th>Name</th>
<th>Parent ID</th>
<th>Edit</th>
<th>Delete</th>
</thead>
</thead>
<tbody>
#foreach($departments as $department)
<tr>
<td>{{ $department->id }}</td>
<td>{{ $department->name }}</td>
<td>{{ $department->parent }}</td>
<td>
Edit
</td>
<td>
<form action="{{ url('department-delete/'.$department->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
See the Departments and Employees
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
Route::get('/page-users/{id}', 'Admin\DepartmentController#usersdep');//show users
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
Department.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $table = 'departments';
protected $fillable = [
'name',
];
protected $primaryKey = 'id';
public function users()
{
// return $this->belongsTo(User::class);
return $this->hasMany(User::class,'department','id');
}
//category has childs
public function childs() {
return $this->hasMany('App\Department','parent','id') ;
/*
childs() method with hasMany relationship.
hasMany relationship in Laravel tell us that they have multiple childs.
Here I am creating relationship based on parent and each category has their parent if parent id is 0 it means it is root category.*/
}
}
create_departments_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDepartmentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('parent');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('departments');
}
}
Alternative answer
Model
A Department model might be associated with one parent. To define this relationship, place a parent method on the model. The parent method should call the hasOne method and return its result:
class Department extends Model
{
protected $fillable = [
'name',
'parent_id',
];
public function parent()
{
return $this->hasOne(Department::class, 'id', 'parent_id');
}
}
Migration
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('departments');
});
Usage
Once the relationship has been defined, you can retrieve the parent :
$departments = Department::get();
foreach ($departments as $department) {
if ($parent = $item->parent) {
dd($department->name, $parent->name);
}
else{
dd('This department is a parent')
}
}
You need to pass the correct department id.
public function index()
{
$departments = DB::table('departments')->select('departments.*')->get();
return view('admin.department', compact('departments'));
}
And view:
#foreach($departments as $department)
<tr>
<td>{{ $department->id }}</td>
<td>{{ $department->name }}</td>
#foreach($departments as $parent)
#if( $department->parent === $parent->id )
<td>{{ $department->name }}</td>
#endif
#endforeach
<tr>
#endforeach
Just define a relation in Department model
public function parentDepartment()
{
return $this->belongsTo(self::class, 'parent');
}
and in index method load it
public function index()
{
$departments = Department::with('parentDepartment')->get();
}

Trying to add data to database, but it's coming in as Null

I'm trying to add 2 fields of input through a modal, but once I hit submit I get an error message saying
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'Flag_Reason' cannot be null (SQL: insert into `Flagged` (`Flag_Reason`, `Other_Comments`) values (, ))
Here's some of my code pertaining to the issue.
Resource & Flag Models
class Resource extends Model
{
protected $table = 'Resources';
protected $primaryKey = 'Resource_ID';
public $timestamps = false;
protected $fillable = [
'Name',
'Description',
'Misc_Info'
];
protected $guarded = [];
/** A resource can have many locations */
public function locations()
{
return $this->belongsToMany('App\Models\Location', 'ResourceLocation', 'Location_ID', 'Resource_ID');
}
public function flag ()
{
return $this->hasMany('App\Models\Flagged');
}
class Flagged extends Model
{
protected $table = 'Flagged';
protected $primaryKey = 'Flag_ID';
public $timestamps = false;
protected $fillable = [
'Flag_Reason',
'Other_Comments',
];
protected $guarded = [];
}
Resource View (modal is triggered in this view)
<table class=" display table table-hover table-bordered" , id="resource">
<thead>
<th>Name</th>
<th>Description</th>
<th>Address</th>
</thead>
<tbody>
#foreach($resources as $resource) #foreach ($resource->locations as $location)
<tr>
<td> <a class="btn btn-small btn-default" style="float:right; margin-right:5px;" href="{{ URL::to('resource/addToCart/' .$resource->Resource_ID) }}">+</a> {{ $resource->Name }}</td>
<td>{{ $resource->Description }}</td>
<td>{{ $location->Address }}</td>
<td>
<button type="button" id="submitFlag" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Flag
</button>
</td>
</tr>
#endforeach #endforeach
</tbody>
</table>
Modal
<div class="modal fade" id="flagResource" tabindex="-1" role="dialog" aria-labelledby="flagModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="flagResourceLabel" style="text-align:center;"> Flagged
</h4>
</div>
<div class="modal-body">
{!! Form::open(array('url'=>'flags', 'class'=>'form', 'method'=>'POST')) !!}
<div class="form-group">
<label for="reason" class="control-label">Reason for Flagging:</label>
{!! Form::text('reason', null, array('class'=> 'form-control', 'placeholder'=>'Reason')) !!}
</div>
<div class="form-group">
<label for="comments" class="control-label">Other Comments:</label>
{!! Form::text('comments', null, array('class'=> 'form-control', 'placeholder'=>'Comments')) !!}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<span class="pull-right">
<button type="button" class="btn btn-primary" style="margin-left:5px;">Submit</button>
</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script>
$('#flagResource').on('show.bs.modal', function(e) {
var submitFlag = $(e.relatedTarget);
var resourceName = submitFlag.data('resource-name');
var resourceId = submitFlag.data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
});
</script>
Flag Controller
public function addFlag($id)
{
$flag = Flagged::create(Request::only(
'Flag_Reason',
'Other_Comments' ));
$flag->save(); \Session::flash('flash_message', 'Flagged!');
return back();
}
Once I input a reason and comments for the flag, I get the above message. What am I doing wrong here? Thanks in advance!
EDIT ROUTES
Route::get('flags', 'FlagsController#index');
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#postFlag']);
Route::get('flags/edit/{Resource_ID}', 'FlagsController#editResource');
Route::patch('flags/edit/{Resource_ID}', 'FlagsController#updateResource');
Route::get('setflag/{Resource_ID}', 'FlagsController#addFlag');
Route::get('pages/editresources/rmflag/{Resource_ID}', 'FlagsController#removeFlag');
Route::get('pages/editresources/rmdelete/{Resource_ID}', 'FlagsController#removeDelete');
Route::get('setdelete/{Resource_ID}', 'FlagsController#addDelete');
Fixed it by changing this in my controller :
$flag = Flagged::create(Request::only(
'Flag_Reason',
'Other_Comments' ));
to this:
public function postFlag()
{
$flag = Flagged::create([
'Flag_Reason' => Input::get('reason'),
'Other_Comments' =>Input::get('comments')]);
$flag->save();
\Session::flash('flash_message', 'Flagged!');
return redirect('resource');
}

Categories