I'm getting the error:
BadMethodCallException in Macroable.php line 74: Method delete does
not exist.
route:
Route::resource('posts', 'PostController');
my controller:
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where('id', $id)->where('user_id',$user_id)->get();
$post->delete();
return view('/home', [
'posts' => $post
]);
}
view:
<form action="{{ route('posts.destroy', '$post->id') }}" method="post">
<input type="hidden" name="_method" value="DELETE" />
{{ csrf_field() }}
{{ method_field('DELETE') }}
<input type="submit" class="btn btn-danger" value="delete" />
</form>
I tried changing method="post" to delete: error is gone but nothing gets deleted..
This is your code.
$user_id = Auth::user();
$post= Post::where('id', $id)->where('user_id',$user_id)->get();
$post->delete();
just add ->each() before delete like this,
$post->each->delete();
It work's for me.
Remove get() and it will work
$post= Post::where('id', $id)->where('user_id',$user_id);
$post->delete();
If you want to delete first document you can use :
$post= Post::where('id', $id)->where('user_id',$user_id)->first();
$post->delete();
However, you always need to check if $post is found as a query document or its null so addd :
if($post){
$post->delete();
}
use ->first() instead of ->get()
you can't delete an entire collection with delete()
Change get for first, and check if the post belongs to the user afterwards.
public function destroy($id)
{
$post = Post::where('id', $id)->first();
if($post && $post->user_id == \Auth::user()->id){
$post->delete();
return view('/home');
}else{
abort(404);
}
}
controller:
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
//redirect to
return redirect()->back();
}
view:
{!! Form::open(['method' => 'DELETE','route' => ['posts.destroy', $post->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
Try this.
hope you created the controller with
--resource
flag.
As post id is primary key of posts table you can directly remove from table,
No need of user_id
To fetch user_id from Auth facade you should use,
$user_id = Auth::id();
Only by passing id should work,
Post::find($id)->delete()
However, if you know the primary key of the model, you may delete the model without retrieving it by calling the destroy method. In addition to a single primary key as its argument, the destroy method will accept multiple primary keys, an array of primary keys, or a collection of primary keys:
Post::destroy($id)
Please Try This:
public function destroy($id)
{
$userId = Auth::user()->id;
$post = Post::where([
'id' => $id,
'user_id' => $userId
])->delete();
Session::flash('success', 'Post was successfully deleted!');
return redirect()->route('posts.index');
}
This is how I am able to delete one (or multiple) associated record(s) in a table:
RFIResponseFile::where('rfi_response_id',$response_id)->delete();
Post::where('id', $id)->where('user_id',$user_id)->delete();
Or
$post= Post::where('id', $id)->where('user_id',$user_id);
if($post->get()->count()){
$post->delete();
}
In your controller
Before change code
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where('id', $id)->where('user_id',$user_id)->get();
$post->delete();
return view('/home', [
'posts' => $post
]);
}
After change code
public function destroy($id)
{
$user_id = Auth::user();
$post= Post::where(['id'=>$id,'user_id'=>$user_id])->get();
Post::where(['id'=>$id,'user_id'=>$user_id])->delete();
return view('/home', [
'posts' => $post
]);
}
Just add this on top of view, i 've error like you and now solved, sorry for bad english.
{!! Form::model($post, ['route' => ['posts.destroy', $post->id], 'method' => 'DELETE']) !!}
and
{!! Form::close() !!}
on bottom
for controller
$post = Post::find($id);
$post->delete();
Session::flash('success', 'Menu was successfully deleted!');
return redirect()->route('posts.index');
I'm trying to have a button pass a query to the database when it's clicked. I'd like to have this set within a Controller that also stores requests and deletes requests. I was able to write to the database using store() and destroy(), but my edit() function gives me routing trouble. What is the best method to edit records using a controller? How would you build the edit() function? Or...should I be using the Update() function? I'm a Laravel/PHP beginner, please explain your answers if you can. Thank you!!
Overview: The project is an employee records table. I want to click a button that changes the employment status of an employee. I already have buttons to add new employee and delete and employee using this same Controller.
This is the route I set for the page:
Route::resource('employees', 'EmployeeController');
This is the front end form code for the button:
$workers = DB::table('employees')->get();
#foreach($workers as $employee)
{!! Form::open(array(
'method' => 'edit',
'route' => [ 'employees.edit', $employee->id]
)
)
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
#endforeach
This is my store function and destroy function:
public function store(Request $request)
{
// Confirm Both Fields Are Not Empty
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
]);
//Add a new employee using the request data
$employee = new Employee;
$employee->first_name = request('first_name');
$employee->last_name = request('last_name');
$employee->position = request('position');
$employee->salary = request('salary');
$employee->hire_date = request('hire_date');
//$employee->attach = request('attach');
//Save it to the database
$employee->save();
//And then redirect back to the Employees page
return redirect('/employees');
}
public function destroy($id)
{
$employee = Employee::find($id);
$destroysignal = $employee->delete();
if($destroysignal) {
return redirect('employees');
}
}
You don't edit records, you update them. In your case you need an update() function in your controller
public function update(Request $request, $id)
{
$employee = Employee::findOrFail($id);
$employee->employment_status = true; //or false or whatever your statuses are
$employee->update();
return redirect()->back()->with('message', 'Employee updated!');
}
In your form, use the update route instead
{!! Form::model($employee, [
'method' => 'PATCH',
'route' => ['employees.update', $employee->id]])
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
When using resource routes, 'route' => [ 'employees.edit', $employee->id] will most like to open a page where you want to edit the object. And the route will be bound to the edit($id) function of your controller.
With that said, the edit route doesn't need a form. A simple anchor would do
Edit Employee
I have an issue with my the update method in my controller.
Normally everything works and it takes care of itself, but this time its not working.
My controller:
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, Vehicle::$rules, Vehicle::$messages);
if ($validation->passes())
{
$this->vehicle->update($id, $input);
return Redirect::route('admin.vehicles.index')->with('success', 'Car Updated');
}
return Redirect::back()
->withInput()
->withErrors($validation);
}
Repository:
public function update($id, $input)
{
print_r($id);
die();
}
This prints out:
{vehicle}
from the URI:
http://localhost/admin/vehicles/1/edit
My form:
{{ Form::open(['route' => 'admin.vehicles.update', 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
// inputs
<div class="form-group">
{{ Form::submit('Update Vehicle', ['class' => 'btn btn-success']) }}
</div>
{{ Form::close() }}
Route:
Route::resource('/admin/vehicles', 'VehiclesController');
Where is this going wrong? How can I get this form to send the ID not the word vehicle?
I am having an issue with my resource route when calling the update method.
I get this error:
Creating default object from empty value
The controller:
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, Vehicle::$rules, Vehicle::$messages);
if ($validation->passes())
{
$this->vehicle->update($id, $input);
return Redirect::route('admin.vehicles.index')->with('success', 'Car Updated');
}
return Redirect::back()
->withInput()
->withErrors($validation);
}
repository:
public function update($id, $input)
{
$vehicle = Vehicle::find($id);
$vehicle->VRM = $input['VRM'];
$vehicle->make = $input['make'];
$vehicle->model = $input['model'];
$vehicle->description = $input['description'];
$vehicle->save();
}
Route:
Route::resource('/admin/vehicles', 'VehiclesController');
If I print the ID then it shows {vehicle}.
My form is this:
{{ Form::open(['route' => 'admin.vehicles.update', 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
// input fields etc
{{ Form::close() }}
I think there is something wrong with the form possibly? Since when the error is thrown the URL is:
http://localhost/admin/vehicles/%7Bvehicles%7D
Never had any issues before with using resource routes with CRUD applications and cant see where this is going wrong?
You need the id in update route...
{{ Form::open(['route' => array('admin.vehicles.update', $vehicle->id), 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
I'm trying building a timer app - this form should submit the time (which it does) AND the client name as populated from the database, it looks like this:
{{ Form::open(array('action' => 'TasksController#store', 'name' => 'timer')) }}
{{ Form::select('client', $client , Input::old('client')) }}
{{ Form::hidden('duration', '', array('id' => 'val', 'name' => 'duration')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
My controller that generates this page looks like this:
public function index()
{
$client = DB::table('clients')->orderBy('name', 'asc')->lists('name','id');
return View::make('tasks.index', compact('task', 'client'));
}
I am getting a "Undefined variable: client" when I submit the form. I can't see why.
What am I doing wrong?
EDIT: the store function in my TasksController looks like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return View::make('tasks.index');
}
return View::make('tasks.index')
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}
You are returning the View::make() from your store() function, which is not the 'resourceful' way of doing it.
Your view is expecting to have $client included in it - but because store() does not return a $client - the error is generated.
Assuming you are using a resourceful controller - your store function should look like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return Redirect::route('tasks.index'); // Let the index() function handle the view generation
}
return Redirect::back() // Return back to where you came from and let that method handle the view generation
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}