Alias column name in view laravel - php

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

Related

Closing the modal after sending the data to the database

I don't use pure vue in the app. I want to close the modal after sending the data to the database. I cannot close it for anything in the world by examining the divergence of the Internet. Can you help? :)
<div class="container-fluid">
<!-- DIRECT CHAT -->
<div class="card" id="form">
<!-- /.card-header -->
<div class="card-body">
<div class="row">
<!-- Button trigger modal -->
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal">
Dodaj budynek
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Dodawanie budynku</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#csrf
#{{ info.data }}
<div class="modal-body">
<div class="form-group">
<label>Nazwa budynku <span class="red">*</span></label>
<input type="text" class="form-control" name="name" id="name" v-model="name">
<small>Nazwa identyfikująca budynek, np. ulica i numer budynku lub nazwa własna</small>
<small><div v-if="feedback">
<span style="color:red" v-text="feedback.name[0]" ></span>
</div></small>
</div>
<div class="form-group">
<label>Konto rozliczeniowe</label>
<input type="text" class="form-control" name="bank_account" id="bank_account" v-model="bank_account">
<small>Numer konta bankowego</small>
</div>
<div class="form-group">
<label>Opis</label>
<textarea class="form-control" rows="3" name="description" id="description" v-model="description"></textarea>
<small>Dodatkowe informacje, adnotacje, opis</small>
</div>
<small><span class="red">* pola obowiązkowe</span></small>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-success" #click="add">Zapisz</button>
</div>
</div>
</div>
</div>
</div>
<div class="row pt-2">
<table class="table table-striped">
<thead>
<tr>
<th scope="col" width="5%">#</th>
<th scope="col" width="25%">Nazwa <i class="fas fa-info-circle fa-sm" rel="tooltip" title="Nazwa pod którą identyfikowana jest zarządzana nieruchomość"></i></th>
<th scope="col" width="30%">Konto księgowe <i class="fas fa-info-circle fa-sm" rel="tooltip" title="Numer konta bankowego"></i></th>
<th scope="col" width="30%">Opis <i class="fas fa-info-circle fa-sm" rel="tooltip" title="Opis identyfikujący lub uzupełniający nazwę zarządzanej nieruchomości"></i></th>
<th width="5%"></th>
<th width="5%"></th>
</tr>
</thead>
<tbody>
<tr v-for="(list, index) in lists" :key="list.id">
<th scope="row">#{{ index + 1 }}</th>
<td>#{{ list.name }}</td>
<td>#{{ list.bank_account }}</td>
<td>#{{ list.description }}</td>
<td><button type="button" class="btn btn-info btn-sm"><i class="fas fa-pencil-alt"></i></button></td>
<td><button type="button" class="btn btn-danger btn-sm" #click="deleteData(list.id)"><i class="far fa-trash-alt"></i></button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
I present script vue below. After running the add method, I would like to close the modal.
<script>
const app = new Vue({
el: '#form',
data () {
return {
feedback: '',
name: '',
bank_account: '',
description: '',
info: '',
lists: [],
}
},
mounted: function(){
this.show();
},
methods: {
show:function(list){
axios
.get('buildings/show', {
})
.then(({ data }) => (this.lists = data));
},
add () {
axios
.post('buildings/store', {
name: this.name,
bank_account: this.bank_account,
description: this.description,
})
.then(response => {
this.show();
this.name = '';
this.bank_account = '';
this.description = '';
this.info = response;
this.myModal.hide();
})
.catch(error => {
this.feedback = error.response.data.errors;
this.info = '';
})
},
deleteData:function(id){
axios
.post('buildings/destroy', {
id: id
})
.then(response => {
this.show();
})
.catch(error => {})
},
},
})
</script>
I wonder how to edit the code so that after calling the add method, the modal will close. I don't want to write in pure vue.js because I haven't grasped this topic yet.
I'm assuming you're using bootstrap modals here?
In your add() method you have this: this.myModal.hide(); but myModal is not defined anywhere.
In your modal html you can add a ref:
<div class="modal fade" ref="myModal" id="exampleModal">
Then you can use this to close the modal:
this.$refs.myModal.hide();
You can take little help of jquery if you already have it.
let currentOpenModel= jQuery('.modal.in').attr('id');
// modalID or undefined
jQuery('#' + currentOpenModel)?.modal('hide');

Add data from a datatable to a modal in laravel

The spanish version failed me, so I'll test my luck here
I have the following code and I would like to know how I can pass the data from my table to the modal
This is my code in edit.blade.php. The modal does work but I don't know how to make the data show up in the modal, I'll do POST to the database myself but I just want to know how I make that data show up so I can edit it.
The data that I want to appear in the modal are the id, the name and the email.
This is my code in editar.blade.php
<script src="{{ url('/js/vendor/jquery-1.12.4.min.js') }} "></script>
<script src="{{ url('/js/bootstrap.min.js') }} "></script>
<link rel="stylesheet" href="{{ url('/css/bootstrap.min.css') }} ">
<script src="{{ url('/js/jquery.dataTables.min.js') }} "></script>
<div class="container">
<h2>Editar estudiante</h2>
<div class="container">
<h2>Laravel DataTables Tutorial Example</h2>
<table id="user_table" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%" id="name">Name</th>
<th width="35%" id="email">Email</th>
<th width="30%">Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="edit-modal-label">Edit Data</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="attachment-body-content">
<form id="edit-form" class="form-horizontal" method="POST">
<div class="card text-white bg-dark mb-0">
<div class="card-header">
<h2 class="m-0">Edit</h2>
</div>
<div class="card-body">
<!-- id -->
<input type="hidden" name="modal-input-id" class="form-control" id="modal-input-id" required>
<!-- /id -->
<!-- name -->
<div class="form-group">
<label class="col-form-label" for="modal-input-name">Name</label>
<input type="text" name="modal-input-name" class="form-control" id="modal-input-name" required autofocus>
</div>
<!-- /name -->
<!-- description -->
<div class="form-group">
<label class="col-form-label" for="modal-input-description">Email</label>
<input type="text" name="modal-email" class="form-control" id="modal-input-email" required>
</div>
<!-- /description -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#user_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getdata') }}",
},
columns: [
{
data: 'name',
name: 'name',
className: 'user-name',
},
{
data: 'email',
name: 'email',
className: 'user-email',
},
{
data: 'action',
name: 'action',
orderable: false
}
]
});
$(document).on('click', "#edit-item", function() {
//obtenemos la instancia de la fila
$tr = $(this).closest('tr');
//rellenamos los campos en el modal
$('#modal-input-name').val($('user-name', $tr).text());
$('#modal-input-email').val($('user-email', $tr).text());
// Mostramos el modal
$('#edit-modal').modal('show');
})
// on modal hide
$('#edit-modal').on('hide.bs.modal', function() {
$('.edit-item-trigger-clicked').removeClass('edit-item-trigger-clicked')
$('#edit-form').trigger('reset');
})
});
</script>
This is my get route in web.php
Route::get('/editar', 'AdminController#editar')->name('editar');
This is my function to bring data to the Datatable in AdminController.php
public function getPosts(Request $request)
{
if($request->ajax()){
$data = StudentModel::latest()->get();
return DataTables::of($data)
->addColumn('action', function($data){
$button = '<button id="edit-item" type="button" name="edit-item" data-target-id="'.$data->id.'" class="edit btn btn-primary btn-sm" data-toggle="modal" data-target="edit-modal">Edit</button>';
$button .= ' <button type="button" name="edit" data-target-id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('editar');
}
Can you try this?
$('#modal-input-name').val($tr.find('td.user-name').text());
$('#modal-input-email').val($tr.find('td.user-email').text());
And also I would suggest that you use a css class for targeting a click event, as Id is normally for a unique identifier, and by doing your way you are having many table rows with the same Id which defeats the original idea.

Cant update form data laravel

I’m trying to update a modal form but for some reason nothing changed after I click the update button. I have tried to dd request->role_name, but it looks like it didn’t catch the value that I input with select form. The delete and create works perfectly fine. I will provide the create and delete controller if you all want to know.
The table that I used:
bas_role
id
name
bas__app
id
app_name
bas_role_app
id
role_id(f_key)
app_name(f_key)
Route:
Route::get('/roleapp', 'RoleAppController#display');
Route::post('/roleapp/update/{roleapp}', 'RoleAppController#update');
Route::get('ajaxdata/getapp','RoleAppController#getroleapp')->name('ajaxdata.getroleapp');
Controller:
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()) {
$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.app_name','=','bas_role_app.app_name')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->distinct()
// ->where('role_user.role_id', 4)
->select('bas_role_app.app_name','bas_role.name','bas_role_app.id','bas_role_app.role_id')
// ->from('bas_app')
// // ->where('role_user.role_id', 4)
->groupBy('bas_app.app_name','bas_role.name','bas_role_app.id')
->Orderby('bas_role_app.id')
->get();
// dd($app);
$bas_role = Role::distinct()->select('id','name')->get();
$bas_app =App::distinct()->select('id','app_name')->get();
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
return view('/roleapp', ['app' => $app, 'bas_app'=> $bas_app, 'bas_role' => $bas_role]);
// return view('/roleapp', ['app' => $app, 'bas_app' => $bas_app]);
}else {
return view("login");
}
}
public function getroleapp(){
$app = DB::table('bas_role_app')
->join('bas_role_app','bas_app.app_name','=','bas_role_app.app_name')
->join('bas_role','bas_role_app.role_id','=','bas_role.id')
->from('bas_app')
->select('bas_role_app.app_name','bas_role.name','bas_role_app.id')
->get();
return Datatables::of($app)->make(true);
}
public function update(Request $request, $id)
{
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
$idUser = Auth::id();
DB::beginTransaction();
DB::table('bas_role_app')
->where('id', $id)
->update([
'role_id' => $request->role_name ,
'app_name' => $request->app_name,
]);
// dd($request->role_name);
return redirect('/roleapp')->with('message', 'Role App data update success!');
} else {
return view("login");
}
RoleApp.blade.php
#extends('layouts.master')
#section('title','Role App')
#section('content')
#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
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<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">Add New Role</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
//Create new role app
<div class="modal-body">
<form action="roleapp/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label">Role Name:</label>
<select class="form-control select2bs4" data-live-search="true" data-placeholder="Choose Role Name" tabindex="1" name="role_name" style="width: 100%;" required>
<option value="">Choose Role Name.......</option>
#foreach ($bas_role as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">App Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose App Name" tabindex="1" name="app_name" style="width: 100%;" required>
<option value="">Choose App Name.......</option>
#foreach ($bas_app as $category)
<option value="{{ $category->app_name }}">{{ $category->app_name }}</option>
#endforeach
</select>
</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>
//show role app table
<table class="table table-striped" id="app">
<thead>
<tr>
<th scope="col">id</th>
<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 RoleApp</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
//Update a role app
<div class="modal-body">
<form id="app_form_{{$p->id}}" action="{{ url('roleapp/update', [$p->id]) }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" form="app_form_{{$p->id}}" />
<div class="form-group">
<label class="control-label">Role Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose Role Name" tabindex="1" name="role_name" style="width: 100%;" required>
<option value="{{$p->id}}">{{$p->name}}</option>
#foreach ($bas_role as $category)
<option value="{{ $p->role_id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">App Name:</label>
<select class="form-control select2bs4" data-placeholder="Choose App Name" tabindex="1" name="app_name" style="width: 100%;" required>
<option value="{{$p->app_name}}">{{$p->app_name}}</option>
#foreach ($bas_app as $category)
<option value="{{ $p->app_name }}">{{ $category->app_name }}</option>
#endforeach
</select>
</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
//delete a roleapp
#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 < 3) {
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": "id" },
{ "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>';
}
},
],
});
$('.selectpicker').selectpicker({
style: 'btn-default',
// size: false
});
} );
</script>
{{--
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> --}}
#endsection
please change the route HTTP verb for update -
Like Below
Route::put('/roleapp/update/{roleapp}', 'RoleAppController#update');
or
Route::match(['PUT','PATCH'],'/roleapp/update/{roleapp}', 'RoleAppController#update')
and update your blade view -
//Update a role app
<div class="modal-body">
<form id="app_form_{{$p->id}}" action="{{ url('roleapp/update', [$p->id]) }}" method="POST">
#method('PUT')
#csrf

cant display all result from 2 table join with pivot table

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;
}
}

Ajax calls problems

I have 2 ajax calls, 1 for create and 1 for delete a folder, here is the source code
<!-- Create folder ajax -->
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$('#create-folder').click(function(e) {
e.preventDefault();
$.ajax({
data: $('#create-folder-form').serialize(),
url: "{{ route('folders.store') }}",
type: "POST",
dataType: "json",
success: function (data) {
if(data.errors) {
alert('Sorry');
} else {
$('#create-folder-form').trigger("reset");
$('#exampleModal').modal('hide');
$('.folders').append('<li data-id=' + data.id + '>' + data.name + " <button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='" + data.id + "'> Delete " + "</button>" + '</li>');
}
},
error: function (data) {
console.log('Error ' + data);
}
})
});
// Delete ajax call
$('.delete-folder').click(function(e) {
let id = ($(this).data('id'));
$.ajax({
type: 'delete',
url: "folders/" + id,
success: function(data) {
$('.folders li[data-id=' + data.id + ']').remove();
}
});
});
});
</script>
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
#include('partials.nav')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Folders</div>
<div class="card-body">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Create folder
</button>
<!-- Modal -->
<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">Create</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="create-folder-form">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" id="create-folder">Create</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row justify-content-center mt-3">
<div class="col-md-8">
<div class="card">
<div class="card-header">Folders</div>
<div class="card-body">
#if($folders)
<ul class="folders">
#foreach($folders as $folder)
<li data-id="{{ $folder->id }}">
{{ $folder->name }}
<button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='{{ $folder->id }}'>Delete</button>
</li>
#endforeach
</ul>
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
Controller
public function index()
{
$user = User::findOrFail(Auth::id());
$folders = $user->folders()->get();
return view('folders.index', compact('folders'));
}
public function store(Request $request)
{
$attributes = $request->validate([
'name' => 'required'
]);
$attributes['user_id'] = Auth::id();
$folder = Folder::create($attributes);
return Response::json($folder);
}
public function destroy(Folder $folder)
{
$folder->delete();
return Response::json($folder);
}
Everything works well, it adds me the element to the DOM, but there is a little problem, when I am trying to delete a folder after i create it, it does not work, I need to refresh my page and then it is working.
Easy mistake to make. jQuery can't find the dynamically added button directly.
Instead of
$('.delete-folder').click(function(e) {...});
use
$('body').on('click','.delete-folder', function(e) {...});

Categories