簡體   English   中英

laravel auth()不允許用戶發出發布請求

[英]laravel auth() is not allowing a user to make a post request

用戶應該能夠為多本書籍設置評分,這允許用戶為僅一本書而不是其他書籍設置評分。

問題

用戶無法對另一本書進行其他評分。 但是,其他用戶可以對同一本書進行評分,但不能對其他書籍進行評分。 即使用戶注銷也不會。

我正在使用rateYolaravel-ratable

我的設置方式是,默認情況下,評分type設置為false,從而使用戶可以設置星星並進行評分。

再一次,一旦用戶對任何一本書進行評級都沒關系,那么評級type將設置為true,從而使用戶無法設置星級。

這是我所擁有的

這是html設置的樣子

HTML

  <div id="rateYo" data-rateyo-rating="{{  $book->userSumRating or 0}}" data-rateyo-read-only="{{ $book->rated ? 'true' : 'false' }}"></div`>

BookController.php

  public function rate(Request $request, $book_id)
    {

        $book = Book::find($book_id);
        $rating = $book->ratings()->where('user_id', auth()->user()->id)->first();

        if(is_null($rating)){
            $ratings = new Rating();
            $ratings->rating =  $request['rating'];
            $ratings->user_id = auth()->user()->id;
            $ratings->type = Book::RATED;
            $book->ratings()->save($ratings);



            return json_encode($book);

        }
        else{
           return response()->json(['status' => 'You already left a review']);
        }
    }

    public function show($book_name)
    {
        $books = Book::GetBook($book_name)->get();


        $data = $books->map(function(Book $book){


            $book['rated'] =  $book->type; 

            return $book;

        });

        return view('books.show', compact('data', $data));
    }

Book.php (相關代碼)默認情況下,如果未設置評分,則類型等於false,使用戶能夠進行評分;如果設置了評分,則類型等於true,從而禁用星號功能/閱讀模式。

use Rateable;

const RATED = "true";
const NOT_RATED = "false";

protected $fillable = [ 'user_id', 'title', 'description'];

protected $appends = ['rated'];


public function getRatedAttribute()
{
    return Rate::where('type',  $this->owl() )->where('user_id', auth()->user()->id )->first();
}


public function owl(){

    foreach($this->rate as $rates){
        if ($rates->type != "true"){
            return self::NOT_RATED;
        }

    }
    return self::RATED;

}


public function rate()
{   
    return $this->hasMany('App\Rate', 'type', 'user_id');
}

您需要在where子句中添加書籍ID,以檢查用戶是否對該書有評分。 有了它,它將找到用戶為任何書籍留下的第一評價。

$constraints = [
    'user_id' => auth()->id(),
    'book_id' => $book_id
];

// checks if the user has not left a rating for this particular book
if ($book->ratings()->where($constraints)->doesntExist()) {
    // create new rating...
} else {
    // user has already rated this book...
}

我需要將“我的書”模型更改為以下模型,謝謝數字化為我指引正確的方向

book.php中

public function getRatedAttribute()
{
    $this->constraints = [
        'user_id' => auth()->id()
    ];

    if(Rating::where($this->constraints)->exists()){

        return Rating::where(['type' => self::RATED, 'book_id' => $this->getKey()])->first();
    }else{
        return Rating::where('type' ,self::NOT_RATED)->first();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM