My function is deleting a different row to the one I intended, Laravel 5.4? - laravel

When I press remove, it removes the last charity in the database that belongs to the current user.
View (Button that deletes):
<a href="#"> <button class="btn btn-danger pull-right btnPopover" data-
toggle="popover" data-placement="top"> Remove </button> </a>
View (JS that is called):
function ConfirmDelete()
{
true;
}
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
content: '<form style="display: inline;" action="{{
URL::to('remove', array($favourite->id)) }} "> <button class = "btn
btn-success glyphicon glyphicon-ok" onclick="return
ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-
danger glyphicon glyphicon-remove"> No </button> '
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
Route:
Route::get('remove/{id}', 'HomeController#removeFavourite');
Controller (removeFavourite function):
public function removeFavourite($id)
{
Favourites::where('id', $id)->delete();
Session::flash('flash_message', 'Removed successfully!');
return back();
}
The strange thing is, is that I am using the exact same function and JS call in another part of the application and it is working fine!
The problem is, that it deletes the last record belonging to that user in the database.
Thanks

I don't know exactly what your code looks like, but the problem is that your JS is only valid for the last iteration of the loop, which sounds like what you're experiencing.
To fix it, you can move the form inside the popover button so that you can get the correct form link:
Example (moving the form):
<button class="btn btn-danger pull-right btnPopover" data-toggle="popover" data-placement="top" data-content='<form style="display: inline;" action="{{ URL::to('remove', array($favourite->id)) }} "> <button class = "btn btn-success glyphicon glyphicon-ok" onclick="return ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-danger glyphicon glyphicon-remove"> No </button> '> Remove </button>
JS:
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
....
This could be a little cleaner if you could access the parent button from the popover, but I couldn't find a way to do that in the API.

Check whether the $id you retrieve in your program(I assume there is some code missing in the question which finds the $id) is the one you want to delete.

Level official documentation says to use following code for deleting models:
$flight = App\Flight::find(1);
$flight->delete();
Find retrieves single model, and where returns a collection, so that might be the issue.
Also make sure that you pass the specific $id of the favourite that needs to be deleted, if not you'll always be deleting the last $id in your loop.
Official Docs

Related

Confirmation window "Cancel" button not working

I'm building my first laravel project and I'm trying to make a confirmation window for my "Delete" button. The thing is that confirmation window shows up, but whether I press "confirm" or "cancel" it would delete data anyway. Can you help me out?
Here is my code:
<a id="demo" href="{{route('viewfile2.delete2', $down->id)}}?{{time()}}">
<button type="submit" class="btn btn-primary" style="background-color:red;"onclick="myFunction()">
Delete
</button>
</a>
<script>
function myFunction(){
return confirm('Are you sure?');
}
</script>
To prevent your form submitting data, replace type="submit" by type="button" and replace your JavaScript code by testing the return value of the confirm call, if it's true then submit your form programmatically.
For testing purposes I made this:
<form id="deleteFormId" action="http://yourwebsite.kom/doDelete/4598765">
<button type="button" onclick='myFunction()'>Delete</button>
</form>
</body>
</html>
<script>
function myFunc(){
if (window.confirm("Are You Sure ?")) {
document.querySelector('#deleteFormId').submit();
}
}
</script>
See the Codepen example and Document.querySelector() documentation.
This is as much as simple
<a href="{{route('viewfile2.delete2', $down->id)}}?{{time()">
<i class="far fa-trash-alt trash_color" onclick="return confirm('If you delete {{$down->id}} it will be permanently deleted\nAre you sure?')"></i>.
</a>

Laravel 2 submit buttons in the same form

I am building a CRUD with Laravel. Each category hasMany attachments and each attachment belongsTo a category.
In the category.edit view I want to give the user the possibility of deleting the attachments (singularly) from the Category. I tried this method but it did not work:
Registering route for the attachment:
Route::group(['middleware' => ['auth']], function () {
Route::delete('attachment/{id}', 'AttachmentController#delete')->name('attachment');
});
Handling the delete building the AttachmentController#delete method:
class AttachmentController extends Controller
{
public function delete($id) {
$toDelete = Attachment::findOrFail($id);
$toDelete->delete();
return redirect()->back();
}
}
In the CategoryController (edit method), I fetch the attachments linked to each category to be rendered inside the view:
public function edit($category)
{
$wildcard = $category;
$category = Category::findOrFail($wildcard);
$attachments = App\Category::findOrFail($wildcard)->attachments()->get()->toArray();
return view('category.edit', [
'category' => $category,
'attachments' => $attachments
]);
}
In the view, I render the attachment and the button to delete. I am fully aware of the error of having a form inside another form, nevertheless I do not know antoher approach to submit this delete request.
// update Category form
#foreach ($attachments as $attachment)
<div class="row">
<div class="col-4">
<img style="width: 100%;" src={{ $attachment['url'] }} alt="">
</div>
<div class="col-4">
<div>
<p class="general_par general_url">{{ $attachment['url'] }}</p>
</div>
</div>
<div class="col-4">
<form action="{{ route('attachment', $attachment['id']) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete Image</button>
</form>
</div>
</div>
<hr>
#endforeach
// end of update Category form
Should I build a deleteAttachment method inside the CategoryController? If so, how can I still submit the Delete request? Also, if any other Model in the future will have attachments, should I build a deleteAttachment method inside each controller? That is cumbersome. Thanks in advance
if you don't like to use form, then use tag:
<a class="btn btn-danger" href="{{ route('attachment', $attachment['id']) }}">Delete Image</a>
And redefine the route to Route::get(...)
(or maybe use ajax for POST method if that is required)

to get data in a modal in Laravel

Is there any way to get the data inside a modal? I know that it is possible to work with this through Jquery, but I would like to know if there is any way to work with Laravel itself. In a view, we can do this:
return view ('admin/users/index', ['datas1' => $ datas1, 'datas2' => $datas2];
but for a modal, is it possible to do something like this? to send my data through the controller and within my modal I check if this data are coming empty or filled, as this answer I just want to show different things, like this:
$dep = User::query()->where('dep_link', $id)->get();
 return['status' => 'success', 'dep' => $dep];
only my validation in the modal:
<div class="row" style="padding: 28px 20px;">
<div class="col-12">
#if(empty($dep))
<div class="position-relative">
<label for="rg_titular">Selecione o RG do titular (.png .jpg .pdf)</label><br>
<input type="file" name="rg_titular" class="file-input"/>
<button type="button" class="file-button">Selecionar arquivo</button>
<span class="text-arquivo">Arquivo selecionado!</span>
</div>
#else
<a href="link" target="_blank">
Visualizar RG do titular
</a>
#endif
</div>
</div>
Is there any way I can get this data inside the modal window and work with them? I just want to check if it's coming empty or not, that's all.
You can write a view composer for the modal blade file.
https://laravel.com/docs/5.8/views#view-composers
In your service provider (app, or a custom one you make)
public function boot()
{
view()->composer('myBladeFileName', function ($view) {
$activeUsers = \App\User::where('active', true)->get();
$view->with(compact('activeUsers'));
});
}

Trying to get property of non-object Laravel

i'm getting trouble in getting the data from foreign key
that i wanna get the information from table media
already make relation between 2 tables, but still error give me this Trying to get property of non-objectin spite of my table have data between those tables
Modal Dossier
public function media(){
return $this->belongsTo('App\Media');
}
Modal Media
public function dossier(){
return $this->hasOne('App\Dossier');
}
and that my view
i sent the variable $dossier and i did loop
i trying to get all info
#if($dossier->media)
<?php $ext=substr($dossier->media->url,-3) ;?>
<label class="med">
#if($ext=='pdf')
<i class="fa fa-file-pdf-o"></i>
#else
<i class="fa fa-file-word-o"></i>
#endif
{{$dossier->media->libelle}}
</label><a class="btn btn-warning btn-small pull-right" href="documents/{{$dossier->media->url}}"><i class="fa fa-print"></i></a>
<br><br>
<button id="btn-add{{$dossier->id}}" class="btn btn-primary">Ajouter un Media</button>
#else
<div class="div1{{$dossier->id}}">
<div class="alert alert-warning">Aucune media</div><button id="btn-add{{$dossier->id}}" class="btn btn-primary">Ajouter un Media</button>
</div>
#endif
Looks like $dossier is null. You should always check if object is null, like:
#if (is_null($dossier) && $dossier->media)
Check your model Dossier, it may be like:
public function media(){
return $this->belongsTo('App\Media', MEDIA_FORIGNKEY);
}
Hope this help you!

angularUI select dropdown displays data only after entering a character

I am using AngularJS v1.2.15 and angular-ui / ui-select. My select HTML is:
<div class="form-group col-md-3">
<div class="input-group select2-bootstrap-append">
<ui-select ng-model="modelOwner.selected" theme="select2" class="form-control">
<match placeholder="Select Owner">{{$select.selected.name}}</match>
<choices repeat="item in owner | filter: $select.search">
<span ng-bind-html="item.name | highlight: $select.search"></span>
</choices>
</ui-select>
<span class="input-group-btn">
<button ng-click="modelOwner.selected = undefined" class="btn btn-danger">
<span class="glyphicon glyphicon-trash"></span>
</button>
</span>
</div>
</div>
My call in controller is:
$scope.modelOwner = {};
OwnersFactory.query({}, function (data) {
$scope.owner = data;
});
My service code:
bootstrapApp.factory('OwnersFactory', function ($http,$state,serviceUrl,$resource,$log) {
return $resource(serviceUrl + 'owner/:id', {}, {
show: { method: 'GET', params: {}, isArray: false }
})
});
Now, in my form i can view the values only after entering at least a single character. I want this select dropdown to display values just by clicking on the dropdown (not by entering any character.)
Possible Solution: if i could load my state only after all the AJAX calls have been made.
Please help me out here.
if you are using ui-router you can use resolve on each state, so that the call is resolved before initializing the controller
https://github.com/angular-ui/ui-router/wiki#resolve

Resources