How do delete single row in pivot table with laravel - php

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

Related

How can I show items belonging to a logged in user in Laravel?

I want to show the emails that the logged in user has sent from the database
This is the route code:
Route::get('/myEmails/{id}','PagesController#myEmailsShow');
This is the function in the controller:
public function myEmailsShow($id)
{
$myEmails = DB::table('emails')->where('user_id',$id)->get();
return view('content.myEmails', compact('myEmails'));
}
This is the a link where the user click to open the page:
#if(Auth::check())
<a class="nav-link text-white" href="/myEmails/{id}"> my emails</a>
#endif
And here where i want to show the data (i am showing only the name for test):
<div class="row">
#foreach($myEmails as $myEmail)
{{$myEmail->name}}
#endforeach
</div>
I think the best way to accomplish your goals here would be using a hasMany relationship between User and Emails (if emails is a Model).
//User.php
public function emails()
{
return $this->hasMany('App\Models\Email');
}
In the controller, apply the Auth middleware to the myEmailsShow method in a constructor:
//PagesController.php
public function __construct()
{
$this->middleware('auth')->only(['myEmailsShow']);
}
Then, in your myEmailsShow method, do something like the following:
//PagesController.php
public function myEmailsShow()
{
// Middleware Eliminates the need for ID in the function.
$user = auth()->user();
$myEmails = $user->emails;
return view('content.myEmails', compact('myEmails'));
}
You can remove the ID parameter from the route and just make it something like Route::get('/myEmails', 'PagesController#myEmailsShow');. Only users who are logged in will be able to access this page, and they will only see emails belonging to them.
Route::get('/myEmails/{user}','PagesController#myEmailsShow')->name('myemails');
with the controller
use App\Email;
use App\User;
public function myEmailsShow(User $user)
{
///calling the model Email at parameters instead of $id eloquent automatically the data from DB
$myEmails = Email::where('user_id',$user->id)->get();
return view('content.myEmails')->with('myEmails', $myEmails);
}
The link has little modifications
#if(Auth::check())
<a class="nav-link text-white" href="{{route('myemails', $user->id)}}"> my emails</a>
#endif
displaying the value
#foreach($myEmails as $myEmail)
{{$myEmail->name}}
#endforeach

Delete products url not working in Laravel

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

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

Laravel Change database column when button is clicked

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!

How do I fetch data based on user id using Laravel 5.4

I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:
public function index(User $id)
{
$user = User::find($id);
$record = $user->diary;
return view('home')->with('record', $record);
}
The blade file it should display to:
#foreach ($record as $diary)
{{ $diary->error }}
{{ $diary->fix }}
#endforeach
In your index function the $id is not integer - this is a User instance, so you can try use this:
public function index(User $user)
{
$record = $user->diary;
return view('home')->with('record', $record);
}

Categories