I am working on the add to favorites and view favorites list functionality on my website. I have managed to create 2 tables
A users tables with id, name, surname, photo, type and email
A favorites tables with id, user_id, favoriteable_id, created_at and updated_at
I was trying to implement it in such a way that when a user, who is connected to his account clicks on the add to favorites button, It will add the user selected on his list of favorites.
I tried doing it this way but it didn't quite worked and got confused in the process.
This is my web routes
Route::post('favorite/{user}', 'FavoriteController@favoriteUser')->name('jobber.fav.store');
Route::post('unfavorite/{user}', 'Favorite@unFavoriteUser');
Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');
This is my Favorite Controller
/**
* Favorite a particular jobber
*
* @param User $user
* @return Response
*/
public function favoriteUser(User $user)
{
Auth::user()->favorites()->attach($user->id);
return back();
}
/**
* Unfavorite a particular post
*
* @param User $user
* @return Response
*/
public function unFavoriteUser(User $user)
{
Auth::user()->favorites()->detach($user->id);
return back();
}
and this is my User Controller
/**
* Get all favorite posts by user
*
* @return Response
*/
public function myFavorites()
{
$myFavorites = Auth::user()->favorites;
return view('users.my_favorites', compact('myFavorites'));
}
And the route that adds to the list of favorites
<div class="col-lg-4">
<a class="apply-thisjob" href="#" title=""><i class="la la-paper-plane"></i>Recherchez d'autres jobbeurs</a>
<a class="add-tofavorite" href=" " title=""><i class="la la-heart-o"></i>Add to my favorites</a>
</div>
And this is my_favorites.blade.php
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="page-header">
<h3>My Favorites</h3>
</div>
@forelse ($myFavorites as $myFavorite)
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
</div>
</div>
@empty
<p>You have no favorite posts.</p>
@endforelse
</div>
and Inside my user Model I added this
public function favorites()
{
return $this->belongsToMany(User::class, 'favorites', 'user_id', 'favoriteable_id')->withTimeStamps();
}
Can Anyone help me out? Or any suggestions on how to make it work.. THanks in advance.
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2vLSHFn
via IFTTT
Aucun commentaire:
Enregistrer un commentaire