最喜欢和最不喜欢的按钮问题laravel

时间:2020-05-21 00:03:31

标签: javascript php jquery ajax laravel

I'm working on a Laravel project where user can favorite and unfavorite books, in the two cases the DB changes successfully without page reloading as i used ajax , but i have two problems: 

-第一个问题:如果没有收藏夹,收藏夹按钮消失,我需要编辑数据库以将一些书添加到收藏夹表中,然后再次显示该按钮。 -第二个问题是,当我刷新页面时喜欢多于一本书时,“喜欢”按钮就会重复。

这是我控制器中的代码:

class FavoriteController extends Controller
{
    public function bookFavBook(Request $request){
        $book_id = $request['bookid'];

        $fav = DB::table('favorites')
        ->where('book_id', $book_id)
        ->where('user_id', Auth::user()->id)
        ->first();
check if books fav or unfav
        if(!$fav){
            $newfav = new Favorite;
            $newfav->book_id =$book_id; 
            $newfav->user_id = Auth::user()->id;
            $newfav->fav = 1;
            $newfav->save();
           to use in ajax
            $is_fav = 1;  
        }
        elseif ($fav->fav == 1){
            DB::table('favorites')
        ->where('book_id', $book_id)
        ->where('user_id', Auth::user()->id)
        ->delete();
        $is_fav = 0;
        }
        elseif ($fav->fav == 0){
            DB::table('favorites')
        ->where('book_id', $book_id)
        ->where('user_id', Auth::user()->id)
        ->update(['fav'=> 1] );
        $is_fav = 1;
        }
        $response = array(
            'is_fav'=>$is_fav,
        );
        return response()->json($response, 200);
    } 

以及我认为的代码:

第一次循环 @foreach($ books as $ book)

            <div class="container-fluid column">
              <div class="row flex-row flex-nowrap">
                <div class="col-md-4">
                  <div class="card card-block">
                    <div>
                      <img
                        class="card-img-top"
                        src="/images/{{ $book-> book_img}}"
                        alt="Card image cap"
                      />
                    </div>

                      <h5 class="card-title"> <a href="/books/{{ $book->id }}">{{ $book ->title}}</a> </h5>
                      <p class="card-text">
                        {{ $book-> description}}
                      </p>
                       <div class="card">

                      <div class="mb-3">
                        <span class="badge badge-pill badge-primary p-2 mr-4">
                          <span class="count_of_book">{{ $book-> amount }}</span>
                          copies available
                        </span>
query books from favorites table
                        @php
                            $getbook = DB::table('books')
                            ->join('favorites','favorites.book_id','=', 'books.id' )
                            ->where('favorites.user_id','=',Auth::id())
                            ->get();
                        @endphp
                         socond loop
                        @foreach($getbook as $fbook) 
                        **@if($fbook->book_id == $book->id )
                        <i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
                        @else
                        <i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
                        @endif**
                        end second loop
                        @endforeach  
                  </div>
                </div>
                end first loop
                @endforeach 
                </div>
                {{ $books->links() }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    var token = '{{ Session::token()}}';
    var urlFav = '{{ route('favor') }}';
    </script>

和js文件中的ajax代码:

     $(".fa-heart").on("click", function (event){
    bookid = $(this).data("bookid");
    $.ajax({
        method: 'POST',
        url: urlFav,
        data: {bookid: bookid , _token:token},
        success: function(data){

            if(data.is_fav == 1){
                $(event.target).removeClass("text-dark").addClass("text-danger");

            }
            if(data.is_fav == 0){
                $(event.target).removeClass("text-danger").addClass("text-dark");
            }
        }

    });[show duplication of the buuton][1]

  [1]: https://i.stack.imgur.com/551I4.png

1 个答案:

答案 0 :(得分:0)

不执行联接查询,而是先获取书籍,然后在for循环内检查收藏夹表中是否存在书籍。如果它们存在并且是最喜欢的,则表明它们是最喜欢的,否则表明它们不是最爱。

@php
  $getbook = DB::table('books')->get();
@endphp

@foreach($getbook as $fbook)
  @php
    $fav = DB::table('favorites')->where(['book_id' => $fbook->id])->get();
  @endphp
  @if($fav != null && $fav->is_fav == 1)
    <i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
  @else
     <i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
  @endif
@endforeach