I'm fairly new to Laravel and would like to create a functionality where I will delete a single record from the database by clicking a link.
Below is the code on the view:
#foreach($companies as $company)
<tr>
<td> {{$company->name}}</td>
<td> {{$company->descriptions}}</td>
<td> {{$company->comptype->name}}</td>
<td>
<i class="fa fa-edit"></i>
<a onclick="
var result = confirm('Are you sure you wish to delete this Company?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
"
class="btn btn-xs btn-default"><i class="fa fa-trash"></i> </a>
<form id="delete-form" action="{{ route('companies.destroy',[$company->id]) }}"
method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
Next is the destroy method in the Controller
public function destroy(Company $company)
{
//
// dd($company);
$findCompany = Company::findOrFail( $company->id);
if($findCompany->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');
}
The form looks like this:
When clicking on trash, to delete a particular record, the record on the table gets deleted and it doesn't matter which I try to delete, the first record always gets deleted. When I did a diedown, I found that the URL has the correct record but dd shows that the first record will be deleted. I am fairly new to Laravel, I've done this using Laravelcollective/html, but unfortunately it's not compatible with Laravel 5.5.28. Please be so kind to assist
The problem is in JS code. Your JS code always sumbits the same delete form. To fix this, you need to use unique IDs:
<form id="delete-form{{ $company->id }}"
And then:
document.getElementById('delete-form{{ $company->id }}').submit();
Also, mixing JS and PHP is a bad practice. You should really put all the JS into a separate JS file.
Try That way it's my project code :
View File :
<td>
<form action="{{action('TagController#destroy', $row['id'])}}" method="post">
{{csrf_field()}}
<input name="_method" type="hidden" value="DELETE">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
TagController.php:
public function destroy($id)
{
$tags = Tag::find($id);
$success = $tags->delete();
if($success)
{
return redirect('/admin/tag')
->with('success','Tag deleted.');
}
return back()->withInput()->with('errors','Some error...');
}
Try this
see the form action "{{ route('companies.destroy',[$company->id]) }}" to {{ url('companies/destroy/'.$company->id) }}
see the destroy methos in wrong
Click the link
Perfect Method
public function destroy($id){
$findCompany = Company::findOrFail($id);
if($findCompany->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');}
Try this code for view file :
<div class="col-xs-12">
<a href="{{url('/delete')}}/{{$allDemos[$i]->id}}" class='btndelete'>
<i class="fa fa-trash"></i>
</a>
SliderControler.php :
public function delete($id){
$Slider = Slider::find($id);
unlink('slider_images/'.$Slider->slider_img);
$Slider->delete();
return redirect('/slider');
}
Try this:
public function destroy(Company $company)
{
if($company->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');
}
Related
I created a resource controller. The problem is when I code a route in my view, the browser displays Route [crops.restore] not defined. I run the php artisan route:list command and I realize that the route does not exist in the route list.
My controller is this
// Display all crops
public function index(Request $request)
{
if ($request->has('trashed')) {
$records = Crop::onlyTrashed()
->get();
} else {
$records = Crop::get();
}
return view('crops.index', compact('records'));
}
//restore a file
public function restore(Request $request, $id)
{
Crop::withTrashed()->find($id)->restore();
return redirect()->back();
}
My route
// Crop controllers
Route::resource('crops', 'CropsController');
My View
#foreach ($records as $crops)
//code ...
#if(request()->has('trashed'))
<a class="btn btn-success btn-sm float-left mr-1" href="/crops/{{ $crops['id'] }}/edit">Edit</a>
Restore
#else
<form method="POST" class="float-left" action="{{ route('crops.destroy', $crops->id) }}">
#csrf
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger delete btn-sm " title='Delete'>Delete</button>
</form>
#endif
#endforeach
What's wrong with my code?
Restore provide this methods in your controller: index, store, edit, update, show, destroy. If you want redirect to your custom method like restore your have to rewrite your route in this matter:
Route::get('/restore', [App\Http\Controllers\CropsController::class, 'restore']);
Just add the route in the web.php file. For example:
Route::get('/restore', '\App\Http\Controllers\HomeController#restore');
I have created an online store, but there is a problem that when I enter the discount code in, the condition is executed correctly and returns a message of success of the operation, but no data for the entered discount code is returned.
the check function
public function coupon_check()
{
$coupon = Coupon::where('code', request()->post('code'))->first();
if (isset($coupon) || !empty($coupon)) {
toast('Successfully !!!', 'success');
return redirect()->back()->with(['coupon'=>$coupon]);
} else {
toast('Not Found !!!', 'error');
return redirect()->back();
}
}
in here
<tr>
<td style="color: white">{{__('discount')}}</td>
<td style="color: white">#if($coupon){{$coupon->discount_value }}
#endif </td>
</tr>
when executing this form
<form action="{{ route('coupons.check') }}" method="POST">
#csrf
<input type="text" name="code" class="form-control text-center" placeholder="
{{ __('cupon code') }}">
<button name="confirm_code" class="btn btn-success col-md">{{ __('Confirm')
}}</button>
</form>
When you use with, you create a session, and to access that session, you should use session helper. So change your if statement like this:
#if(session('coupon')){{session('coupon')->discount_value }}
I am using Laravel 7 and am stuck on trying to initiate a Controller method via a button in my view. I am using a form with a simple a tag but am not sure if how I am going about it is the best way. Besides, I am getting an error withe the way I am attempting it. The error is:
Too few arguments to function App\Http\Controllers\TasksController::finished(), 1 passed in C:\laragon\www\taskapp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
I am truly stumped on how to call a method from a button click. What I am trying to do is (when the button is clicked) change the status of an item in my db called $task->task_status to "Complete".
In my table in the home view, I have a form like this:
<td>
<form method="POST" action="/tasks/{{$task->id}}">
{{ csrf_field() }}
{{ method_field('POST') }}
<div class="ml-5">
<i class="fa fa-check"></i>
</div>
</td>
In my web.php, I have:
Route::get('/finished/{id}', 'TasksController#finished')->name('finished');
And in my TasksController, I have the following:
public function finished(Request $request, $id) {
$task = Task::find($id);
dd($task);
$task->task_status = $request['task_status'] = 'Completed';
$task->save();
return redirect('home')->with('success', 'Task Completed and now viewable in Completed Tasks!');
}
If anyone can show me a better way of accomplishing this (without using axaj) I would really appreciate it.
Thank you in advance.
I ended up fixing this in using the following code:
in my web.php, I used:
Route::get('/finished/{id}', 'TasksController#finished');
in my home.blade.php, I have:
<td>
<form action="finished/{{$task->id}}" method="GET" style="display: inline" class="">
#csrf
#method('POST')
<div class="ml-5">
<button type="submit" class="btn btn-sm btn-success">
<i class="fa fa-check"></i>
</button>
</div>
</form>
</td>
And in my TasksController, I pretty much left that the way it was and it now works.
I have a form associated with the destroy method to delete a item/record.
<form action="{{ route('climb-excluded.destroy',$exclude->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o" aria-hidden="true"></i> Delete
</button>
</form>
destroy() method
<?php
public function destroy(Cexcluded $cexcluded)
{
$cexcluded->tours()->detach();
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
Routes
Route::resource('climb-excluded','CexcludedsController', ['only'=>['store','destroy']]);
Route::get('climbing/included-excluded','HomeController#getclimbIE')->name('climb.ie');
The trouble I'm having is the destroy method is not deleting the record from the DB and doesn't give any error. It is giving a session message without deleting the record.
I saw your other thread with the same issue regarding the detach causing problems.
Add this to your Cexcluded model
public static function boot()
{
parent::boot();
static::deleting(function($model) {
$model->tours()->detach();
});
}
Remove the following line from your controller method
$cexcluded->tours()->detach();
So try this
public function destroy(Cexcluded $cexcluded)
{
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
You must use "->destroy()" in the controller.
Check this question for clarification between destroy() and delete()
Destroy method not working
I am trying to delete an image from my database but I am receiving the following error:
Undefined variable: portfolio (View: C:\MyProjects\bubblehouseProject\resources\views\admin\portfolio\addPortfolio.blade.php)
I believe there is something wrong with the logic I am trying to implement in my Laravel application. I am using Eloquent ORM.
Controller:
public function Destroy($id) {
$portfolio = new Portfolio();
$portfolio::find($id);
$portfolio->delete();
return redirect('addPortfolio')->with('delete', 'The image has been successfully deleted!');
}
Route:
Route::get('addPortfolio/{id}', 'AddPortfolioController#Destroy');
View:
<form action="{{ route('addPortfolioController.Destroy', $portfolio->id) }}">
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
{{ method_field('DELETE') }}
</form>
I am not entirely sure that this is the right way to delete data from the database.
Route
Route::delete('addPortfolio/{id}', 'AddPortfolioController#Destroy')->name('portfolio.destroy');
View
<form action="{{ route('portfolio.destroy', $portfolio->id) }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
</form>
Controller
public function destroy($id)
{
if(Portfolio::destroy($id)) {
return redirect('addPortfolio')->with('success', 'The image has been successfully deleted!');
} else {
return redirect('addPortfolio')->with('error', 'Please try again!');
}
}