Laravel 5.2 - Delete from db - php

I am using Laravel Framework version 5.2.45.
I have created a simple view that outputs my todos:
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
Within my routes I have created the following route to delete a todo:
Route::get('/todo/delete/{id}', [
'uses' => 'TodosController#delete',
'as' => 'todo.delete'
]);
Within my TodosController I created the following delete method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Todo;
class TodosController extends Controller
{
public function delete($id) {
$todo = Todo::find($id);
$todo->delete();
return redirect()->back();
}
// ...
When I press the button in the frontend nothing happens. I do not get any error...
Any suggestions what is wrong with my implementation?
Appreciate your replies!

You are using button not tag
turn your code from
#foreach($todos as $todo)
{{ $todo->todo }} <button href="{{ route('todo.delete', ['id' => $todo->id]) }}" class="btn btn-danger">x</button>
<hr>
#endforeach
to
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach

Try Below code, You have used a button instead of a tag
#foreach($todos as $todo)
{{ $todo->todo }} x
<hr>
#endforeach

You should do like this :
Delete Button :
<a class="btn btn-primary" href="{{ route('todo.delete',$todo->id) }}">Delete</a>
And delete function look like below :
public function delete($id) {
try {
$delete_flag = Todo::where(['id' => $id])->first();
$delete_flag->delete();
return redirect()->back()->with('success', 'Todo deleted successfully');
} catch (Exception $ex) {
return redirect()->back()->with('error', 'Something went wrong');
}
}

#foreach($todos as $todo)
{{ $todo->todo }} x
#endforeach
delete code--
$toDo = Todo::findOrFail($id)->delete();
if($toDo){
return response()->josn(['message'=>'deleted']);
}

Related

Trying to delete record by CRUD route::delete method(Laravel 5.3)

I have a problem with Larave's framework program with deleting by CRUDS method DELETE.
My route method is:
Route::delete('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete(); return redirect('cats.index')
->withSuccess('Cat
has been deleted.'); });
My view with delete url:
#extends('layouts.master')
#section('header')
Back to the overview
<h2>
{{ $cat->name }}
</h2>
<a href="{{ url('cats/'.$cat->id.'/edit') }}">
<span class = "glyphicon glyphicon-edit"></span>
Edit
</a>
<a href ="{{ url('cats/'.$cat->id.'/delete') }}">
<span class ="glyphicon glyphicon-trash"></span>
Delete
</a>
<p>Last edited: {{ $cat->updated_at }}</p>
#endsection
#section('content')
<p>Date of Birth: {{ $cat->date_of_birth }} </p>
<p>
#if ($cat->breed)
Breed:
{{ url('cats/breeds/'.$cat->breed->name) }}
#endif
</p>
#endsection
My Cat model:
<?php
namespace Furbook;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model {
// We specified the fields that are fillable in the Cat model beforehand
protected $fillable = ['name','date_of_birth','breed_id'];
// informacja o tym, żeby nie uaktualniać update_at w tabeli kotów
public $timestamps = false;
public function breed(){
return $this->belongsTo('Furbook\Breed');
}
}
?>
When I'm clicking on delete link, there is an error like this:
MethodNotAllowedHttpException in RouteCollection.php line 233:
I don't know what's wrong. Could you somoene help me with solving problem?
Could someone help me with this problem?
I would be very grateful, greetings.
This is to do with the Request you are making. You must either create form with the delete method like so
<form action="{{ url('cats/'.$cat->id.'/delete') }}" method="DELETE">
<button class ="glyphicon glyphicon-trash">Delete</button>
</form>
OR change your route to a get
Route::get('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete();
return redirect('cats.index')->withSuccess('Cat has been deleted.');
});
If you go the form route don't for get to add the {{ csrf_field() }}
https://laravel.com/docs/5.4/csrf
Using Route::delete(), you cannot place it in an anchor. Make a form with DELETE method.
{!! Form::model($cat, ['method' => 'DELETE', 'url' => 'cats/'.$cat->id.'/delete']) !!}
<button type="submit">Delete</a>
{!! Form::close() !!}

Delete Function: Laravel 5

new to laravel framework here. I'm having quite a problem here calling out the delete function in my resource controller. Seems like it is not deleting the selected id. Thanks for your help in advance.
resources/views/bufashaccts/allAccounts.blade.php
#extends('adminlte::page')
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>view accounts!</h1>
#foreach($bfaccounts as $userAccount)
<p>{{ $userAccount->acct_firstname }}</p><br>
<p>{{ $userAccount->acct_middlename }}</p><br>
<p>{{ $userAccount->acct_lastname }}</p>
#if ($userAccount->id)
<form action="/Accounts" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<a href="/Accounts">
<button type="button">delete</button>
</a>
</form>
#endif
<a href="/Accounts/{{ $userAccount->id }}/edit">
<button type="button">edit</button>
</a>
#endforeach
</body>
</html>
app/http/controllers/AccountsController.php
<?php
namespace App\Http\Controllers;
use App\bufashaccounts;
use Illuminate\Http\Request;
class AccountsController extends Controller
{
public function index()
{
$bfaccounts = bufashaccounts::all();
return view('bufashaccts.allAccounts', compact('bfaccounts'));
}
public function create()
{
return view('bufashaccts.addAccounts');
}
public function store(Request $request)
{
bufashaccounts::create($request->all());
return "success!";
}
public function show($id)
{
$bfshowAccounts = bufashaccounts::findOrFail($id);
return view('bufashaccts.viewAccounts', compact('bfshowAccounts'));
//return $bfshowAccounts;
}
public function edit($id)
{
$bfeditAccounts = bufashaccounts::findOrFail($id);
return view('bufashaccts.editAccounts', compact('bfeditAccounts'));
}
public function update(Request $request, $id)
{
$bfeditAccounts = bufashaccounts::find($id);
$bfeditAccounts->update($request->all());
return redirect('Accounts');
}
public function destroy($id)
{
//$bfdeleteAccounts = bufashaccounts::findOrFail($id);
//$bfdeleteAccounts->delete();
//return 'delete';
$bfaccounts = bufashaccounts::findOrFail($id);
$bfeditAccounts->delete();
//return view('bufashaccts.allAccounts', compact('bfaccounts'));
return redirect('/Accounts');
}
}
You would need to change your form to be something like:
<form action="{{ url("/Accounts/$userAccount->id") }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">delete</button>
</form>
Hope this helps!
Add this in your route file
Route::delete('account/delete/{id}', ['as' => 'account.delete', 'uses' => 'AccountsController#destroy'])
Modify your blade file
<form action="{{ route('account.delete') }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger">Delete</button>
Try this way. Hope it will work.

Update multible rows in laravel 4

I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.
I wanted to now if there is a better way to do this.
The homecontroller with the updatePersons function:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
the view with the form
#extends('layouts.master')
#section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
#foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
#endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
#stop
The routes:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController#updatePersons'));
I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.
If you're updating many rows with each with different values, there's no easier way to do it.
Could you think of how you'd write this in SQL?

Laravel delete with confirm

I try to delete with confirm like, using a controller method delete:
function delete($id) {
$list = Todolist::find($id);
return view('lists.delete')->with('list',$list);
}
and corresponding delete.blade.php:
{!! Form::open(array('route' => array('lists.destroy', $list->id), 'method' => 'delete', 'class' => 'form')) !!}
<button type="submit" class="btn btn-sucess">Delete</button>
<button type="submit" onClick="history.back()">Cancel</button>
{!! Form::close() !!}
then also a controller destroy-method
function destroy($id) {
$list = new Todolist;
//$list->delete($id);
echo
return view('lists.confirmdelete')\Redirect::route('lists.index')
->with('message', 'Task deleted!');
////how to aply 5 second sleep for showing message 'Task deleted!'???
}
and confirmdelete.blade.php
<h1>{{ $list->name }}</h1>
<p>{{ $list->description }}</p>
<p><b>{{ $message }}</b></p>
How to do, that it display "Task deleted!" messsage e.g 5 seconds and then two steps back to an index action?
In your destroy method you have to do a little tweek & also have to use a little bit of js
Change destroy method this to
function destroy($id) {
$list = new Todolist;
$data = [
'name' => $list->name,
'description' => $list->description,
];
$list->delete($id);
$data['message'] = 'Task deleted!';
$data['redirectRoute'] = route('lists.index');
return view('lists.confirmdelete', $data);
}
and in confirmdelete.blade.php
<h1>{{ $name }}</h1>
<p>{{ $description }}</p>
<p><b>{{ $message }}</b></p>
<script>setTimeout(function(){ window.location.href = '{{ $redirectRoute }}' }, 5000);</script>
Easier with:
<button class="btn btn-link"
onclick="return confirm('Are you sure you want to delete the record {{ $user->id }} ?')">
DELETE
</button>
In this case, you open a popup with a confirmation if you want to delete a record before clicking. Obiously you need to put
$user = User::find($id);
in the delete method if you want an id in the message.
session variable best for given problem
try in controller method
function destroy($id) {
//AFTER SUCCESS YOUR LOGIC
Session::flash('message', 'Status Changed');
Session::flash('alert-class', 'alert-success');
return redirect('/index');
}
in blade file you can check like this demo
#if(Session::has('message'))
<div class="alert {{ Session::get('alert-class') }} fade-in" id="alert">
×
{{ Session::get('message') }}
</div>
#endif
Session flash is best to use here it will poof once it print. and you can use JS for after 5 second fadeout.
<script>
$("#alert").fadeTo(2000, 500).slideUp(500, function(){
$("#alert").slideUp(500);
});
</script>

Laravel Getting Error with Validations

I am trying to Get Validation Errors on index.blade.php having issues:
When I fill both the fields then it goes well if i just put an Echo or Return in getLogin Controller.
When I just fill one field and it works good if i just put and echo or Return but not giving validation errors, with Validation Errors it only shows, "Something went Wrong"
Code for index.blade.php
<section class="mainWrap">
<div class="headingfirst"><img src="{{ URL::asset('css/des.png') }}" width="78"></div>
<div class="sedhead">Hey User!!!! Try to Login</div>
<div class="againtext">Sign In To Your Account</div>
<article class="FormContainer">
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
<img class="profile-img" src="{{ URL::asset('css/avatar_2x.png')}}">
{{ Form::open(array('class'=> 'SetMe')) }}
{{ Form::text('email',null, array('placeholder'=>'Email','class'=>'insi')) }}
{{ Form::password('password',array('placeholder'=>'Password','class'=>'dnsi')) }}
{{ Form::submit('Sign In', array('class'=>'SignIn')) }}
{{ Form::close() }}
</article>
</section>
Code for AuthController.php
<?php
class AuthController extends Controller{
public function GetLogin() {
return View::make('layouts.index');
}
public function LogInfo() {
$rules = array('email' => 'required','password' =>'required');
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::route('login')
->withErrors($validator);
}
else{
}
}
}
Code for Routes.php
Route::get('login', array('uses'=>'AuthController#GetLogin' ));
Route::post('login', array('uses'=>'AuthController#LogInfo'));
even when i put the Auth Code it don't show anything except "Something goes wrong". but while working with just Echos it works properly
In validation failed statement,
You need to use return Redirect::to('login') instead of return Redirect::route('login').
In index.blade.php, it should be like -
#foreach($errors->all() as $error)
<div class="errors">{{ $error }} </div>
#endforeach
instead of
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
Also here is my suggestion. if you are currently developing an application using laravel, it is the best to enable debug. Open laravel/app/config/app.php and make sure 'debug' => 'true'. It will help you see what is detailed error messages with stack traces.

Categories