Laravel Change database column when button is clicked - php

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!

Related

Run Livewire click method based on whether a checkbox is checked or not

I have a Livewire component like below
<div class="mr-3">
<input type="checkbox" name="milestoneMark" value="{{ $milestoneId }}" x-model="milestone" wire:click="mark()">
</div>
The component class have below code
class CheckMilestone extends Component
{
public $milestoneId;
public function mark()
{
$milestone = Milestone::where('id', $this->milestoneId)
->first();
$user = User::where('id', auth()->id())
->first();
$user->milestones()->attach($milestone);
}
public function unMark()
{
$milestone = Milestone::where('id', $this->milestoneId)
->first();
$user = User::where('id', auth()->id())
->first();
$user->milestones()->detach($milestone);
}
public function render()
{
return view('livewire.check-milestone');
}
}
My requirement is execute mark() method when the checkbox is unchecked and execute unMark() when the checkbox is checked
I tried below but didn't work
<div class="mr-3">
<input type="checkbox" name="milestoneMark" value="{{ $milestoneId }}" x-model="milestone" {!! 'checked' ? wire:click="mark()" : wire:click="unMark()" !!} >
</div>
I try to use as less JavaScript as possible so if you can please give me a solution without JS, but if there isn't any other way to fix this I'm okay to use JS. TIA!
You have nothing to base your checked situation from. I personally would do the following:
class CheckMilestone extends Component
{
public $milestoneId;
public bool $checked = false;
public function processMark()
{
if ($this->checked) {
$this->mark();
} else {
$this->unMark();
}
}
// Rest of your code here
}
<div class="mr-3">
<input type="checkbox" wire:model="checked" wire:change="processMark()" wire:loading.attr="disabled">
</div>
To explain; we use wire:model to link the value of the checkbox to the Livewire component. We use wire:change to detect the change event triggered when you (de)select the checkbox, and fire the processMark method. Purposely we don't change the HTML as to not cause unexpected behaviour. We use wire:loading to add the disabled attribute while the checked variable is being updated, so we can't quickly uncheck it while it's processing.

I got new function for API Controller and it's not working at this

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){}

How do delete single row in pivot table with laravel

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();

How to fix MethodNotAllowedHttpException error in Laravel 5.7?

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

Attempt to update users table generates MethodNotAllowedHttpException, Laravel-4

UsersController:
public function update($id)
{
if( ! $this->user->isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
$user = $this->user->find($id);
$user->save();
return Redirect::route('users.index');
}
Route:
Route::resource('users','UsersController');
Model:
protected $table = 'users'
edit.blade.php:
{{ Form::model($user, array('route'=>array('users.update','$user'=>'id'))) }}
I notice that this does NOT generate a "PUT" action. The page source:
<form method="POST" action="https://zocios.com/users/id" accept-charset="UTF-8"><input name="_token" type="hidden" value="...">
Hitting the Update User button gets me:
Exception \ MethodNotAllowedHttpException
Is the problem "$user->save();"? Something else I'm doing wrong? Thanks!
You need to specify the method:
{{ Form::model($user, array('method' => 'put', 'route'=>array('users.update','$user'=>'id'))) }}
There is no other method than GET and POST that is accepted (despite the specs), so the framework does the job of identyfying hidden input in your form _method to make it work.

Categories