validating bootstrap modal in laravel - php

im working with laravel And i have bootstrap modal i want to become required the fields. i tried this one required in my input tag and textarea and its not working . i tried to validate in the fields in controller but it wont work i know there something wrong in what im doing. im just beginner in laravel. help me out
this is my 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 info-color white-text">
<h4 class="title">
<i class="fa fa-pencil"></i> New Message</h4>
<button type="button" class="close waves-effect waves-light" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label for="defaultFormEmailModalEx">Recipient</label>
<input type="email" name="recipient" id="defaultFormEmailModalEx" class="form-control form-control-sm" autocomplete="off" v-model="recipient">
<br>
<label for="defaultFormMessageModalEx">Your message</label>
<textarea type="text" name="newmessage" id="defaultFormMessageModalEx" class="md-textarea form-control" v-model="newMessage"></textarea>
<div class="text-center mt-4 mb-2">
<button class="btn btn-info" #click="sendNewMessage">Send
<i class="fa fa-send ml-2"></i>
</button>
</div>
</div>
</div>
</div>
this what #click="sendNewMessage" do
sendNewMessage(){
axios.post('http://localhost/sendnewmsg', {
recipient: this.recipient,
newMessage: this.newMessage
})
.then( (response) => {
console.log(response.data);
/*if(response.status===200){
app.messages = response.data;
app.privateMsg = response.data;
}*/
})
.catch(function (error) {
console.log(error);
});
this.recipient='';
this.newMessage='';
},
and this is the controller i think here must be put the validation
public function sendnewmessage(Request $request){
$recipient = $request->recipient;
$newmessage = $request->newMessage;
$checkUser = DB::table('users')->where('email','=', $recipient)->get();
if($checkUser->isEmpty()){
echo 'data doesnt exist';
}
else{
echo 'data exist';
}
}

You can pass manual validators in your sendnewmessage function,
Please check the below code.
public function sendnewmessage(Request $request){
$validator = \Validator::make($request->all(), [
'recipient' => 'required',
'newMessage' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
$recipient = $request->recipient;
$newmessage = $request->newMessage;
$checkUser = DB::table('users')->where('email','=', $recipient)->get();
if($checkUser->isEmpty()){
echo 'data doesnt exist';
}
else {
echo 'data exist';
}
}
And if you want to show errors on your modal you can write this in your modal
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Hope this will help you comment if you have any query.

Here is what you want...
$this->validate($request, [
'recipient' => 'required',
'newmessage' => 'required',
]);
Here is validate document for laravel
And to show error messages in js you can get erros and store it in a variable
let $errors = response.responseJSON;

Related

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

Laravel 6 : Deleting user while still logged in

Currently i am developing a website. I am working on CRUD for one of my features and have had no problems up until the delete point. I am using bootstrap modal window as a warning window that pops up to clarify that you wish to delete your account. The code for that view and pop-up window looks like this:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<img src="{{ asset('/uploads/avatars/' . $user->avatar ) }}" style="width:100px; height:100px; float:left;
margin-right:25px ">
<strong>Delete {{$user->name}}'s account?</strong></div>
<div class="card-body">
<form action="delete" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="name">Account Email:</label>
<input type="text" name ="email" value="{{$user -> email}}" class="form-control" readonly>
<div class="form-group">
<div class="text-centre">
<p></p>
<button type="button" data_userid="{{$user->id}}" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">
Delete
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
<form action="{{ route('delete', $user)}} " method="post">
{{method_field('delete')}}
{{csrf_field()}}
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to permanetly delete your account?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
<button type="submit" class="btn btn-danger">Yes, delete my account</button>
</div>
</form>
</div>
</div>
</div>
My Routes for this page and function look like so:
Route::get('/users/delete', 'Admin\UsersController#index')->name('delete');
Route::delete('admin/users/{user}', 'Admin\UsersController#destroy')->name('users.destroy');
public function destroy($id,Request $request)
{
$user = User::where("id","=",$id)->first();
$user->delete($id);
if ($user->delete())
{
return Redirect::route('home')->with('global', 'Your account has been deleted!');
}
}
ALso, whenever i try to access the page from a dropdown menu with route
<a class="dropdown-item" href="{{ route('users.destroy', $user)}}">
Delete Account
I am met with a blank page, i am sure this is down to the parameter. So just to clarify,
Whenever the modal window pops up and the user hits "Yes, delete my account" nothing happens and the window stays open, and my routing to the page
{{ route('users.destroy', $user)}}
leads to a blank page.
Any help is greatly appreciated!
Change
<form action="{{ route('delete', $user)}} " method="post">
to
<form action="{{ route('delete', ['user' => $user]) }}" method="post">
in modal.
Also
<a class="dropdown-item" href="{{ route('users.destroy', $user)}}">Delete Account </a>
Does not work because it is a GET request. Deleting should be a DELETE request.
So you should open the modal with the click;
Delete Account
According to your configuration it looks like you are using the wrong alias name for the form and anchor. You should switch them.
This is your route config:
Route::get('/users/delete', '[...]')->name('delete');
Route::delete('admin/users/{user}', '[...]')->name('users.destroy');
This is how you should use them:
On your <a/> you should use route('delete')
On your <form/> you should use route('users.destroy', ['user' => $userId]).
And your delete action should look like this:
Delete the user
Logout the current user
Redirect somewhere
public function destroy($id)
{
User::find($id)->delete();
Auth::logout();
return Redirect::route('home')
->with('global', 'Your account has been deleted!');
}
Hope this helps.
This is how we try to delete Laravel
public function destroy(User $user)
{
$user->delete();
return Redirect::route('home')->with('global', 'Your account has been deleted!');
}
u can do it using ajax and sweetalert to it's more interactive for ui
in you blade file
#foreach($user as $u)
Delete
#endforeach
in your blade bottom you can call ajax request
<script>
$(document).on('click','.delete',function()
{
var id = $(this).data('id');
swal({
title: 'Are you sure you want to delete this?',
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn btn-danger m-btn m-btn--pill m-btn--icon m-btn--air",
confirmButtonText: '<span><i class="la la-thumbs-up"></i> Yes, Delete it!</span>',
cancelButtonClass: 'btn btn-secondary m-btn m-btn--pill m-btn--icon m-btn--air',
cancelButtonText: '<span><i class="la la-thumbs-down"></i>No, thanks</span>',
}).then(function(e){
if(e.value){
$.ajax({
url:"{{route('admin.document.delete')}}",
type:'POST',
headers:{ 'X-CSRF-Token' : jQuery('meta[name=csrf-token]').attr('content') },
dataType:'json',
data:{'id':id,_token: '{{csrf_token()}}'},
success:function(response){
var msg = response.msg;
if(response.status=='success'){
//here you can do whatever after delete msg
//for reload u can use - (location.reload);
}
},
});
}
});
});
</script>
and finally in your controller
public function destroy(Request $request)
{
$id=$request['id'];
$delete = manageMultipleDocument::find($id)->delete();
//optional
$flashArr = array(
'msg' => 'Document deleted successfully.',
'status' => 'success'
);
//optional
$request->Session()->flash('succ_message',$flashArr);
//Required return any thing
return $flashArr;
}

If the user enters the incorrect credentials, display a modal with an error

When the user enters one or more wrong credentials, a modal appears. The problem is that I don't know how I can make this connection from controller to view. Would an ajax be needed, probably?
Controller:
public function login()
{
return view('login');
}
public function logar(Request $req)
{
$data = $req->all();
$verify = Auth::attempt(['email' => $data['email'], 'password' => $data['password']]);
$this->validate($req, [
'email' => [
'required',
'email',
]
]);
if ($verify) {
return redirect()->route('shop.index');
}
return redirect()->route('shop.login');
}
View:
<form class="login-form needs-validation" method="POST" action="{{ route('loja.logar') }}" novalidate>
<meta name="csrf-token" content="{{ csrf_token() }}">
#csrf
<div class="form-group">
<input type="email" class="form-control w-50 mx-auto my-0 py-4" id="email" name="email" aria-describedby="emailHelp" placeholder="Email" required>
</div>
<div class="form-group">
<input type="password" class="form-control w-50 mx-auto my-0 py-4" id="password" name="password" placeholder="Senha" required>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-outline-primary mt-2 py-3 px-4">Enviar</button>
</form>
<div class="modal fade" id="modal1" 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="exampleModalCenterTitle">Error</h5>
</div>
<div class="modal-body">
Login or password incorrect! Try again.
</div>
</div>
</div>
</div>
You have two actually different cases, validation and verification. If the verification error message uses modal, does the validation error message use it too?
NO (Short Answer)
if ($verify) {
return redirect()->route('shop.index');
}
return redirect()->route('shop.login', ['status' => 'error']);
#if(request()->input('status') == 'error')
<div class="modal fade" id="modal1" 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="exampleModalCenterTitle">Error</h5>
</div>
<div class="modal-body">
Login or password incorrect! Try again.
</div>
</div>
</div>
</div>
#endif
#if(request()->input('status') == 'error')
<script type="text/javascript">
$("#modal1").modal('show');
</script>
#endif
YES (Long Answer)
I don't know what $this->validate does, but I assume it's the same thing as validate method provided by the Illuminate\Http\Request object.
If you look at the default LoginController, you will find that the verification error message is the same as validation, using:
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
That means, you will have one action for both. But in your case, you separate them.
/******** VALIDATION ********/
// if validation fails, an exception will be thrown and
// the proper error response will automatically be sent back to the user.
$input = $req->validate($req, [
'email' => ['required', 'email'],
'password' => ['required'],
]);
/******** VERIFICATION ********/
$verify = Auth::attempt(['email' => $data['email'], 'password' => $data['password']]);
if ($verify) {
return redirect()->route('shop.index');
}
// return redirect()->route('shop.login', ['status' => 'error']);
// or
return redirect()->route('shop.login')
->with('status-verification', 'Login or password incorrect! Try again.');
#if($errors->any())
<div class="modal fade" id="modal-validation" 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="exampleModalCenterTitle">Error Validation</h5>
</div>
<div class="modal-body">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
</div>
</div>
#endif
#if(session('status-verification'))
<div class="modal fade" id="modal-verification" 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="exampleModalCenterTitle">Error</h5>
</div>
<div class="modal-body">
{{ session('status-verification') }}
</div>
</div>
</div>
</div>
#endif
<script type="text/javascript">
#if($errors->any())
$("#modal-validation").modal('show');
#endif
#if(session('status-verification'))
$("#modal-verification").modal('show');
#endif
</script>
You can use this script where you want to call the modal.
<script type="text/javascript">
$("#modal1").modal();
</script>
or
<script type="text/javascript">
$("#modal1").modal('show');
</script>
Requires bootstrap and jquery libraries to work.
If you don't want to use template, I think you should use ajax to retrive validation..
But I think you should definately use templates to make it simpler... Obviously, ajax can handle it, but I don't think ajax is going to be right solution for these kind of problems. Sorry, as I am saying so much about template, but i found it dissapointing seeing you not using templates
Visit blade template and
Visit twig template

Laravel populate data on redirect route

I'm doing a error exception where display a modal popup when fail to delete an entry due to parent constrain
Controller :
public function deleteUnitType(Request $request, $proj_id)
{
$id = $request->id;
$unit_types = UnitType::where('id', $id);
$floors = UnitTypeFloor::where('unit_type_id', $id)->get();
if(count($floors) != 0){
return redirect()->route('dev-admin.projects.unit-types.index', ['unit_types' => $unit_types, 'proj_id' => $proj_id, 'floors' => $floors])->with('failed', 'Unit Type failed to delete due to existing floor plan.');
} else {
// $unit_types->delete();
return redirect()->route('dev-admin.projects.unit-types.index', ['unit_types' => $unit_types, 'proj_id' => $proj_id])->with('status', 'Unit Type is successfully deleted.');
}
}
HTML :
<div class="col-12">
#if (session('status'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('status') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#elseif (session('failed'))
<div class="modal fade" id="unit-type-notification-modal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>{{ session('failed') }}</p>
<ul>
#foreach($floors as $floor)
<li>{{ $floor -> name }}</li>
#endforeach
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#endif
</div>
$( document ).ready(function() {
#if (session('failed'))
$('#unit-type-notification-modal').modal('show');
#endif
});
The modal popup and everything but for some reason it cannot find my $floor variable, it says :
Undefined variable: floors
but when I dd it on my controller, the data exist
I think you should check the first session has 'failed' following way.
#if(Session::has('status'))
#elseif( Session::has( 'failed' ) )
And your script:
$( document ).ready(function() {
#if(Session::has('failed'))
$('#unit-type-notification-modal').modal('show');
#endif
});
Thanks
You can add another with to your redirect route
return redirect()->route('dev-admin.projects.unit-types.index', ['unit_types' => $unit_types, 'proj_id' => $proj_id, 'floors' => $floors])
->with('failed', 'Unit Type failed to delete due to existing floor plan.')
->with('floors', $floors);
Or this;
return redirect()->route('dev-admin.projects.unit-types.index', ['unit_types' => $unit_types, 'proj_id' => $proj_id, 'floors' => $floors])
->with(['failed' => 'Unit Type failed to delete due to existing floor plan.', 'floors' => $floors]);

Ajax with laravel and jquery

I am new to laravel and even more with ajax, I am trying to update from ajax but I can not do anything, it stays frozen and after a few seconds the url is updated with the data that happens to it, but in the base data nothing happens. If you could correct the code I would appreciate it because I am sure that this is the one that is giving problem because of my lack of experience, thank you very much
Route:
Route::name('appointments.update')->put('/appointment/$id', 'AppointmentController#update');
html:
<div class="modal fade" id="UpdateEventModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Update</h4>
</div>
<form class="form-horizontal">
<div class="modal-body">
#include('appointments._form-appointments')
</div>
<div class="modal-footer">
<div class="col-md-12 form-group">
{{ Form::submit('Update',['class' => 'btn btn-primary','id' => 'btn-modal-update',]) }}
{{ Form::button('Close',['class' => 'btn btn-default', 'data-dismiss' => 'modal']) }}
</div>
</div>
</form>
</div>
</div>
ajax:
$(document).ready(function() {
$('#btn-modal-update').click(function(){
var id = $('#appointment_id').val();
var route="{{url('appointments.update')}}/"+id+"";
$.ajax({
type:'PUT',
headers:{"Authorization": localStorage.getItem('token')},
url:route,
dataType:'json',
data: {startTime: $('input#startTime').val(), finalTime: $('input#finalTime').val(), patient_id: $('select[name="patient_id"').val(),
user_id: $('select[name="user_id"').val(event.user_id), date: $('input#date').val(), appointment_id: $('#appointment_id').val()},
success:function(data){
if(data.success == 'true'){
alert('updated');
}
},
error:function(data){
alert('not updated');
}
});
});
});
controller:
public function update(Request $request, $id)
{
if($request->ajax()){
$appointment = Appointment::find($id);
$appointment->date = $request->date;
$appointment->startTime = $request->startTime;
$appointment->finalTime = $request->finalTime;
$appointment->clinic_id = $request->clinic_id;
$appointment->user_id = $request->user_id;
$appointment->patient_id = $request->patient_id;
$result = $appointment->save();
if (result) {
return response()->json(['success'=>'true']);
}
else{
return response()->json(['success'=>'false']);
}
}
}
You should change your event listener a little bit:
Listen to the submit() event on your form and make sure that you prevent the normal form submission by adding the following line at the end of the callback: return false;
If it still isn't doing anythin, check your console for error output.

Categories