I added a CRUD interface for my user's table, and instead of a delete button, I used a block button. Which blocks a user (sets bloque field in the database from 0 to 1). I added a new function in my controller called block which is supposed to do the job yet I get a MethodNotAllowedHttpException error every time I click the blocking button.
UserController
public function block($id)
{
$user = User::find($id);
$user->bloque = 1;
$user->save();
return redirect('/users')->with('success', 'Utilisateur bloqué');
}
The blocking HTML fragment
<form action="{{ route('users.block', $user->id)}}" method="get">
#csrf
<!-- #method('DELETE')-->
<button class="btn btn-danger" type="submit">Bloquer</button>
</form>
Routes
Route::get('/block', [
'uses' => 'UserController#block',
'as' => 'users.block'
]);
I think the problem is related to id value, It should be instantiated from $request object. Like:
public function block(Request $request)
{
$user = User::find($request->id);
$user->bloque = 1;
$user->save();
return redirect('/users')->with('success', 'Utilisateur bloqué');
}
Related
I coded update status for category. I got a new function in an API
Controller, so when I click submit it is not working.
This is solved when I move to category.update, but I can't because that function is used for something else.
web.php
Route::patch('category/{$category}', 'Admin\CategoryController#change')
->name('category.change');
Route::resource('category', 'Admin\CategoryController')
->middleware('loggedin');
This is the new function for API Controller:
public function change($category, Request $request)
{
$cate = Category::find($category);
if ($cate->category_status == 0) {
$cate->category_status = 1;
$cate->save();
} else {
$cate->category_status = 0;
$cate->save();
}
return back()->with('success', 'Success!');
}
list.blade.php
<form autocomplete="off" action="{{ route('category.change', [$cate->category_id]) }}" method="POST" enctype="multipart/form-data">
#method('PATCH')
#csrf
<button class="fa fa-eye" type="submit"></button>
</form>
First, in route, delete $
Route::patch('category/{category}', 'Admin\CategoryController#change')
->name('category.change');
Second - use route with named param
route('category.change', ['category' => $cate->category_id])
Third - in controller action Request must be first
public function change(Request $request, $category){}
I want to delete a single row of data in my pivot table. I don't get any error but when try to click on the button. It did not redirect me to anywhere so the delete function is not performed.
In the picture above I want to delete the highlighted id for user_id = 3
My scenario is that the user suddenly can't make it to even_id = 6 so the user wants to delete/unjoined the event.
route
Route::get('/user/event/{event}', 'HomeController#destroy')->name('user.event.destroy');
blade
#foreach ($events as $event)
<tr>
<td>{{$loop->index +1 }}</td>
<td>{{$event->event_name}}</td>
<td>{{$event->event_date}}</td>
<td>
<form method="POST" action="{{ route('user.event.destroy',$event)}}">
#csrf
#method('DELETE')
<a class="btn btn-danger">Unjoined!</a>
</form>
</td>
</tr>
#endforeach
controller
public function storeEventUser(Request $request)
{
$user = User::find(Auth::user()->id);
//how I storing my pivot data (just to show if anyone asking)
$user->events()->syncWithoutDetaching([$request->event_id]);
}
public function destroy($event)
{
$event= Event::findOrFail($event_id);
$user->events()->detach($event);
return redirect()->back()->with('success','Deleted.');
}
Event model
public function users()
{
return $this->belongsToMany(User::class,'event_user','event_id','user_id');
}
user model
public function events()
{
return $this->belongsToMany(Event::class,'event_user','user_id','event_id');
}
I am adjusting your controller method to use Route Model Binding for simplicity:
public function destroy(Event $event)
{
Auth::user()->events()->detach($event);
// or from the other side of the relationship
// $event->users()->detach(Auth::user());
return redirect()->back()->with('success', 'Deleted.');
}
As stated in the comments you need to adjust your route to Route::delete if you want to use the DELETE HTTP method that your form is spoofing via the #method('DELETE') blade directive.
Side note:
Auth::user() returns a User instance so you don't need to query for it again, in your storeEventUser method:
$user = Auth::user();
I want a user to delete a product when he clicks unlike button but I'm getting an error 404 url not found, but I have the url.
If I put dd($product) before $like = Like::findOrFail($product);
it displays the id(4) but if I put dd($like), then it throws an error 404. How can I make this function work?.
Controller
public function destroy($product)
{
$like = Like::findOrFail($product);
dd($like);
$like->delete();
return 'done';
}
Blade
<a class="remove" href="{{ route('product.unlike', ['product' => $product->id]) }}" > Unlike </a>
Route
Route::get('product/{product}/unlike', ['as' => 'product.unlike', 'uses' => 'LikeController#destroy']);
Like.php
class Like extends Model
{
use SoftDeletes;
protected $table = 'likeables';
protected $fillable = [
'user_id',
'product_id',
'likeable_id',
'likeable_type',
];
public function products()
{
return $this->morphedByMany('App\Product', 'likeable');
}
delete request should be post request not get
web.php
Route::delete('product/{product}/unlike','LikeController#destroy')->name('product.unlike');
blade.php
<form action="{{ route('product.unlike',[$product->id]) }}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="remove"> Unlike </button>
</form>
controller
use App\Product;
...
public function destroy(Product $product) {
$product->delete();
return 'done';
}
Hope this helps!
Detach the Products corresponding to the like.
public function destroy($product)
{
Like::where('product_id', $product)
->where('user_id', auth()->user()->id)
->delete();
return 'done';
}
findOrFail will throw an exception which will cause the 404 when it can't find a record. You are using SoftDeletes so the record can exist in the database but doesn't mean that it hasn't been 'soft deleted'. If it has been soft deleted the scope will make it act like it isn't there.
Check your record with id == 4 to see if it has a deleted_at column with a value. If it does, it was deleted (soft deleted). You will have to adjust your query to be able to retrieve soft deleted records.
Laravel 6.x Docs - Eloquent - Soft Deletes - Querying Soft Deleted Models
I want to change the status of a task to complete. I have a status_id column in the database and 1 equals complete. I would like the click of the button to change the status_id to 1
My route
Route::patch('/tasks/completed/{Task}', 'TasksController#completedUpdate')->name('completedUpdate');
My button
<form action="{{ route('completedUpdate', $task->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<button type="submit" class="button is-inverted" style="margin-top: 10px;">Mark Complete</button>
</form>
My controller
public function completedUpdate(Request $request, $task)
{
$task->status_id = $request->status_id;
$task->save;
return redirect()->back()->with('message', 'task marked complete');
}
the error it gives me is:
Attempt to assign property of non-object
Let me know if any more info is needed
You should change:
public function completedUpdate(Request $request, $task)
{
$task->status_id = $request->status_id;
$task->save;
return redirect()->back()->with('message', 'task marked complete');
}
into:
public function completedUpdate(Request $request, Task $task)
{
$task->status_id = $request->status_id;
$task->save();
return redirect()->back()->with('message', 'task marked complete');
}
so you need to typehint type of $task variable and use save() method instead of save property.
Also probably instead of:
/tasks/completed/{Task}
you should use:
/tasks/completed/{task}
$task->save; should be $task->save();
With ->save, it is looking for a property on the model, hence the error message re 'assigning a property'. Whereas ->save() calls the save method on the object.
In your controller, you're assigning the $task->status_id a value of $request->status_id but you're actually not passing the status_id in your form in your HTML code. You can put a hidden element in your form which is <input name="status_id" value="1" />.
In the meanwhile, do not forget that $task->save; must be $task->save();
Good luck!
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