Laravel populate data on redirect route - php

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]);

Related

How to open modal with specific information in it

I want to open a modal with information about the offer that is grabbed from the database.
Here's what I have so far: (Minimal required code)
Opening modal:
<a href="" data-bs-toggle="modal" data-bs-target="#infoPonuka">
<i class="fa-solid fa-eye spc"> </i>
</a>
Modal:
<div class="modal fade" id="infoPonuka" tabindex="-1" aria-labelledby="infoPonuka" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="infoPonuka">Ponuka - info:</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#if(isset($_GET['id']))
#foreach ($ponuky AS $item)
#if($item->ID == $_GET['id'])
#php
$ponuka = $item;
#endphp
{{Debug::printr($ponuka, false);}}
#endif
#endforeach
#endif
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvoriť</button>
</div>
</div>
</div>
</div>
When I was doing it, I thought I could maybe just use $_GET to get the ID of the offer, so I can have specific data from an array because every opening modal (the first code block) is shown on every item, so I wanted to make it unique for every button by maybe adding the href="?id={{ $ponuka->ID }}". But I was unable to do so. Does someone have any idea?
You might use ajax request on click of your anchor tag instead of using these attributes data-bs-toggle="modal" data-bs-target="#infoPonuka", and then, in response of your ajax request, set the data in the html of the modal as Passing ajax response data to modal
and then show the modal as:
$("#modalId").modal("show");
right after the line your data is set to modal html.
Make a method in a Controller and a route:
This will retun a redered view.
public function getOffer($offer_id)
{
$offer = Offer::where('id', $offer_id);
$renderedOfferView = view('modal.offer', ['offer' => $offer)->render();
return return response()->json(['status' => 'success', 'renderedOfferView' => $renderedOfferView]);
}
In your blade:
<a href="" data-bs-toggle="modal" data-bs-target="#infoPonuka" onclick="getOffer('{{ $ponuka->ID }}')">
<i class="fa-solid fa-eye spc"> </i>
</a>
<div class="modal fade" id="infoPonuka" tabindex="-1" aria-labelledby="infoPonuka" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="infoPonuka">Ponuka - info:</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="getOfferContent">
<!-- use the getOfferContent id to fill with data -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvoriť</button>
</div>
</div>
</div>
</div>
getOffer(id){
$('#getOfferContent').html(''); // clear data
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/your-getOffer-route',
type: 'GET',
data: {
id: id,
},
success: function( response ) {
$('#getOfferContent').html(response.renderedOfferView); // fill data
},
error: function( response ) {
}
});
}
Do not forgot to set: <meta name="csrf-token" content="{{ csrf_token() }}"> in your layout.blade.php into <head> tag

validating bootstrap modal in laravel

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;

Pass data from laravel controller to Modal

I want to edit in Modal, but the data does not come through to opgaveRet.blade.php containing Modal :-( Here is my code:
Can anyone help me to see what I am doing wrong?
// route.php
Route::resource('/admin/opgave', 'Admin\OpgaveController');
// OpgaveController.php
public function edit($id)
{
$tasks = Tasks::findOrFail($id);
return view('admin.opgaver.opgaveRet', ['tasks' => $tasks ]);
// also tried :-(:
//return view('admin.opgave', compact('tasks'));
}
// opgave.blade.php
#foreach ($opgaver as $opgave)
// here is a table, and then comes the Action
<a href="{{ route('opgave.edit', $opgave->id) }}"
data-toggle="modal"
data-target="#RetOpgave"
class="btn btn-primary btn-xs">Edit</a>
#endforeach
// in bottom of opgave.blade.php
// #include('admin.opgaver.opgaveRet')
<div class="modal fade" id="RetOpgave" tabindex="-1" role="dialog" aria-labelledby="RetOpgave">
<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="RetOpgave">Ret opgave</h4>
</div>
<div class="modal-body" >
#if(!empty($tasks))
// Here i want to build a FORM::
// But there is nothing in $tasks ???????
{{ dd($tasks) }}
#endif
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Luk</button>
</div>
</div>
</div>
</div>
You have to call the edit function in AJAX.
this one may help you:
https://tutorials.kode-blog.com/laravel-5-ajax-tutorial

Laravel 5 Update existing in database

I'm trying to update an existing row in my table using a form in a bootstrap modal. But nothing changes when I attempt it. I have an html table with a list of cars and in each row a button "Change Status" that opens the bootstrap modal with the id="myModal_{{ $car->id }}" and with the form inside it to edit the status of a car in repair.
Here's my modal:
<!-- Modal -->
<div class="modal fade" id="myModal_{{ $car->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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">Breyta stöðu bíls</h4>
</div>
<div class="modal-body">
<div class="form-group">
<h3>Breyta stöðu fyrir {{ $car->LicencePlate }}</h3>
</div>
{!! Form::open(['url' => 'create']) !!}
<div class="form-group">
{!! Form::label('Status', 'Status: ') !!}
{!! Form::select('Status', [
null => ' -- Veldu Stöðu bíls -- ',
'Í Biðröð' => 'Í Biðröð',
'Í Viðgerð' => 'Í Viðgerð',
'Tilbúinn' => 'Tilbúinn'
], null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{!! Form::submit('Skrá stöðu', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
Update method in CarController:
public function CarEdit($id, Requests\CreateCarsRequest $request)
{
$edit = Car::update($request->all());
return redirect::back();
}
My Route to that method:
Route::post('/dashboard', 'CarController#CarEdit');
You should do this:
['action' => 'CarController#CarEdit']
Also, you're using mass assignment, so you must fill $fillable array in your Car model to make it work:
https://laravel.com/docs/5.1/eloquent#mass-assignment
I was able to fix this with the help of my colleagues. What I did was I created a new requet called UpdateCarRequest where the LicencePlate field was not unique. And edited my method like so:
public function CarEdit(Requests\UpdateCarRequest $request)
{
$edit = Car::where('LicencePlate', '=', $request->LicencePlate)->first();
$edit->update($request->all());
return redirect('/dashboard');
}
I also added a hidden field in the form with the value $car->LicencePlate.

laravel Sending values to blade

I'm having a register form and login form on my home page
the login form is activated when you press the login link (via bootstrap)
and the register form is visible all the time
now when one off those fails, I wanna send the error's to the page
but I can only access the var's of these:
return Redirect::to('/')->withErrors($validator)
->withInput(Input::except('password'));
but when I add ->with('method', 'login') I can't check in my home page the var $method
it's empty and never get's any values
can someone tell me what I might be doing wrong?
and also how I can activate the login form with variables that I send with the ->with()
the login form is made up like this:
<div class="modal fade bs-example-modal-sm pvvoModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login to your account</h4>
</div>
{{ Form::open(array('url' => 'admin/login', 'class'=>'form', 'role' => 'form')) }}
<div class="modal-body">
#if ( $errors->first('username') != null || $errors->first('password') != null)
<div class="alert alert-danger">
<p>Some errors occured</p>
{{ $errors->first('username') }}
{{ $errors->first('password') }}
</div>
#endif
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
{{ Form::text('username', $value = null, array('placeholder' => 'Username', 'class'=> 'form-control', 'required' => 'required', 'autofocus' => 'autofocus' )) }}
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-asterisk"></span></span>
{{ Form::password('password', array('placeholder' => 'Password', 'class' => 'form-control', 'id'=>'password', 'required' => 'required')) }}
</div>
</div>
<div class="text-center">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{{ Form::submit('Login', array('class' => ' btn btn-primary')) }}
</div>
</div>
{{ Form::close() }}
</div><!-- /.modal-content -->
</div>
</div>
</div>
The with() method flashes data to the session, you have to retrieve your data using Session::get()method.
Source : Laravel doc
Fixed it by doing it via AJAX :)
was easier for keeping the login form open

Categories