Delete Function: Laravel 5 - php

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.

Related

Laravel 5.2 - Delete from db

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

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() !!}

Laravel 4 Form Submission and Input Retrieval

I am a beginner in Laravel. I am trying to make a simple login form, by using a controller to manipulate the input. However everytime the code just ignore the controller function and keep calling the index everytime I submit. Please advise.
Here is the code for my form
{{ Form::open(array('action' => 'CoverController#authent')) }}
<div class="col-md-3 text-box pull-left">
{{ Form::email('email', '', array('placeholder'=>'Email')); }}
</div>
<div class="col-md-3 text-box pull-left">
{{ Form::password('password', array('placeholder'=>'Password')); }}
</div>
<div class="clearfix"> </div>
<div class="con-button">
{{ Form::submit('Sign Up / Log In'); }}
</div>
{{ Form::close() }}
Below is my routes
Route::get('/',array('as'=>'users','uses'=>'CoverController#index'));
Route::post('/','CoverController#authent');
Here is my controller function
class CoverController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$view = View::make('cover');
return $view;
}
public function authent()
{
$email = Input::get('email');
$pwd = Input::get('password');
$view = View::make('formoid')->with('email',$email)->with('password',$pwd);
return $view;
}
}
With the above code,everytime the login button is pressed, the index() function is called instead of authent(), what am I doing wrong?
Try:
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
Form Doc

Is there a better way to send variables to blade?

I'm still learning Laravel and how the blade system all works..
I'm wondering what the better way of doing something is and that something is; I've done a query to pull a row from the database and then I want to put that query into an array so I can pick out whatever column I want.
Then I want to pass that to my home.blade.php and be able to use {{ $name }} for example. T
This is what I've got:
TO NOTE: THIS WORKS THE WAY I WANT IT TO BUT IM SURE IM DOING IT THE LONG WAY (WRONG) ROUND.
HomeController.php
<?php
class HomeController extends BaseController {
public function home() {
$hero_query = DB::table('heros')->where('owner_id', Auth::user()->id)->pluck('hero');
if($hero_query) {
$owner_id = Auth::user()->id;
$user = DB::table('heros')->where('owner_id', $owner_id)->first();
$name = $user->hero;
$level = $user->level;
$exp = $user->exp;
$str = $user->str;
$atk = $user->atk;
$def = $user->def;
$int = $user->int;
$blk = $user->blk;
return View::make('home', array(
'name' => $name,
'level' => $level,
'exp' => $exp,
'str' => $str,
'atk' => $atk,
'def' => $def,
'int' => $int,
'blk' => $blk
));
} else {
return View::make('home');
}
}
}
home.blade.php
#if($hero = DB::table('heros')->where('owner_id', Auth::user()->id)->pluck('hero'))
<form action="{{ URL::route('hero-delete') }}" method="POST">
Your hero:<br>
<b>{{ $hero; }}</b> | <input type="submit" value="Delete"><br>
<b>Stats:</b>
LvL: {{ $level }}
Exp: {{ $exp }}
Str: {{ $str }}
Atk: {{ $atk }}
Def: {{ $def }}
Int: {{ $int }}
Blk: {{ $blk }}
</form>
#else
<form action="{{ URL::route('hero-create') }}" method="POST">
Hero:<br>
You do not have a hero, create one!
<input type="text" name="hero">
<input type="submit" value="Create hero">
#if($errors->has('hero'))
{{ $errors->first('hero')}}
#endif
{{ Form::token()}}
</form>
#endif
Now I'm sure I'm doing it in some stupid moronic way as I'm just starting out.. but could someone explain where I'm going wrong?
Thanks in advance!
Just pass the entire $user to the view
$user = DB::table('heros')->where('owner_id', $owner_id)->first();
return View::make('home', array('user' => $user));
Then in your view
Str: {{ $user->str }}
Int: {{ $user->int }}
and so on.
You're doing lots of things wrong :(
I fix a little bit the code, but I didn't test it, so use this as a guide to implement what you want.
class HomeController extends BaseController {
public function home() {
$hero = Hero::where('owner_id', '=', $owner_id)->first();
if($hero)
{
return Response::make('home', array('hero' => $hero->toArray()));
}
else
{
return Response::make('home');
}
}
}
The blade template
#if(isset($hero))
{{ Form::open(array('route' => 'hero-delete', 'method' => 'DELETE')) }}
Your hero:<br>
<b>{{ $hero->hero }}</b> | <input type="submit" value="Delete"><br>
<b>Stats:</b>
<!-- Here you can implement a foreach for performance -->
LvL: {{ $hero->level }}
Exp: {{ $hero->exp }}
Str: {{ $hero->str }}
Atk: {{ $hero->atk }}
Def: {{ $hero->def }}
Int: {{ $hero->int }}
Blk: {{ $hero->blk }}
{{ Form::close() }}
#else
{{ Form::open(array('route' => 'hero-create')) }}
Hero:<br>
You do not have a hero, create one!
<input type="text" name="hero">
<input type="submit" value="Create hero">
#if($errors->has('hero'))
{{ $errors->first('hero')}}
#endif
{{ Form::close() }}
#endif

Laravel 4 displaying flash message doesn't work

I'm trying to display some flash messages, after I have successfully logged in. Can somebody help me understand why nothing is shown ?? Although I know the Session is true?`
This is my Sessions Controller:
class SessionsController extends \BaseController {
public function create()
{
return View::make('sessions.create');
}
public function store()
{
$attempt = Auth::attempt([
'email' => $input['email'],
'password' => $input['password']
]);
if($attempt) return Redirect::intended('/')->with('flash_message', 'You have been logged in!');
dd('problem');
}
public function destroy()
{
Auth::logout();
return Redirect::home();
}
}
And here is my view where the message should be displayed:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Yes</title>
</head>
<body>
<main>
#if(Session::get('flash_message'))
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#endif
<div class="container">
#yield('content')
</div>
</main>
</body>
</html>
I also tried this:
#if(Session::get('flash_message'))
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#else
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#endif
But nothing get's displayed, just an empty nothingness, just like no message was parsed to the view.
Thanks for helping me out :)
In your store function, before if you should add:
Session::flash('flash_message', 'You have been logged in!');
This is used to store flash data in session. The with method won't work in a way you intend.
And then in view:
#if(Session::has('flash_message'))
{{ Session::get('flash_message') }}
#endif

Categories