Как использовать пакет в laravel

Я хочу использовать этот пакет https://github.com/AbdullahGhanem/rating . У меня возникли проблемы при его использовании. Я установил пакет.Я хочу знать, где я должен разместить этот код$post->averageRating(), и я создал рейтинг в Controller. Это правильный путь?

Вот мой код макета:

<html>
<head>
</style>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script  src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


</head>
<body>
<div class="row new-post">
    <div class="col-md-6 col-md-offset-3">

        <header><h3>Comments</h3></header>
        <form action="/comments" method="post">
        {{csrf_field()}}
            <div class="form-group">
                <textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your review on above game"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Post  Comment</button>

        </form>
    </div>
  </div>



    @foreach($comments as $comment) 
<h1>{{$comment->body }}</h1>
@endforeach

{{$post->averageRating();}}
</body>

</html>

Вот мой код контроллеров:-

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppComment;
use Auth;

use IlluminateSupportFacadesDB;




class CommentsController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return IlluminateHttpResponse
 */
public function index()
{
    //
}

/**
 * Show the form for creating a new resource.
 *
 * @return IlluminateHttpResponse
 */
public function create()
{
    //
    $comments = comment::all();
    $post=Post::all();
return view('comments.create', ['comments' => $comments]);


}

/**
 * Store a newly created resource in storage.
 *
 * @param  IlluminateHttpRequest  $request
 * @return IlluminateHttpResponse
 */
public function store(Request $request)
{


    $comment= new Comment();
    $comment->user_id=Auth::user()->id;
    $comment->body=$request->body;
    $comment->save();
    return back();

  $user = User::first();
  $post = Post::first();

  $rating = $post->rating([
  'rating' => 5
   ], $user);

 dd($rating);

 }

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return IlluminateHttpResponse
 */
public function show()
{
    //

}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return IlluminateHttpResponse
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  int  $id
 * @return IlluminateHttpResponse
 */
public function update(Request $request, $id)
{
    //
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return IlluminateHttpResponse
 */
public function destroy($id)
{
    //
}


}

вот мой код модели :-

<?php

namespace App;

use GhanemRatingContractsRating;
use GhanemRatingTraitsRatingable as RatingTrait;
use IlluminateDatabaseEloquentModel;

class Post extends Model implements Rating
{
//


use RatingTrait;
}

вот код в web.РНР:-

Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');
//comments
Route::resource('comments','CommentsController');
//like
Route::post('/like', [
'uses' => 'LikeController@postLikePost',
'as' => 'like'
]);

код в моем приложении.РНР

<?php

return [

/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/

'name' => 'Laravel',

/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/

'env' => env('APP_ENV', 'production'),

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => env('APP_DEBUG', false),

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => env('APP_URL', 'http://localhost'),

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/

'fallback_locale' => 'en',

/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/

'log' => env('APP_LOG', 'single'),

'log_level' => env('APP_LOG_LEVEL', 'debug'),

/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    IlluminateAuthAuthServiceProvider::class,
    IlluminateBroadcastingBroadcastServiceProvider::class,
    IlluminateBusBusServiceProvider::class,
    IlluminateCacheCacheServiceProvider::class,
    IlluminateFoundationProvidersConsoleSupportServiceProvider::class,
    IlluminateCookieCookieServiceProvider::class,
    IlluminateDatabaseDatabaseServiceProvider::class,
    IlluminateEncryptionEncryptionServiceProvider::class,
    IlluminateFilesystemFilesystemServiceProvider::class,
    IlluminateFoundationProvidersFoundationServiceProvider::class,
    IlluminateHashingHashServiceProvider::class,
    IlluminateMailMailServiceProvider::class,
    IlluminateNotificationsNotificationServiceProvider::class,
    IlluminatePaginationPaginationServiceProvider::class,
    IlluminatePipelinePipelineServiceProvider::class,
    IlluminateQueueQueueServiceProvider::class,
    IlluminateRedisRedisServiceProvider::class,
    IlluminateAuthPasswordsPasswordResetServiceProvider::class,
    IlluminateSessionSessionServiceProvider::class,
    IlluminateTranslationTranslationServiceProvider::class,
    IlluminateValidationValidationServiceProvider::class,
    IlluminateViewViewServiceProvider::class,

    /*
     * Package Service Providers...
     */

    //

    /*
     * Application Service Providers...
     */
    AppProvidersAppServiceProvider::class,
    AppProvidersAuthServiceProvider::class,
    // AppProvidersBroadcastServiceProvider::class,
    AppProvidersEventServiceProvider::class,
    AppProvidersRouteServiceProvider::class,
    GhanemRatingRatingServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App' => IlluminateSupportFacadesApp::class,
    'Artisan' => IlluminateSupportFacadesArtisan::class,
    'Auth' => IlluminateSupportFacadesAuth::class,
    'Blade' => IlluminateSupportFacadesBlade::class,
    'Bus' => IlluminateSupportFacadesBus::class,
    'Cache' => IlluminateSupportFacadesCache::class,
    'Config' => IlluminateSupportFacadesConfig::class,
    'Cookie' => IlluminateSupportFacadesCookie::class,
    'Crypt' => IlluminateSupportFacadesCrypt::class,
    'DB' => IlluminateSupportFacadesDB::class,
    'Eloquent' => IlluminateDatabaseEloquentModel::class,
    'Event' => IlluminateSupportFacadesEvent::class,
    'File' => IlluminateSupportFacadesFile::class,
    'Gate' => IlluminateSupportFacadesGate::class,
    'Hash' => IlluminateSupportFacadesHash::class,
    'Lang' => IlluminateSupportFacadesLang::class,
    'Log' => IlluminateSupportFacadesLog::class,
    'Mail' => IlluminateSupportFacadesMail::class,
    'Notification' => IlluminateSupportFacadesNotification::class,
    'Password' => IlluminateSupportFacadesPassword::class,
    'Queue' => IlluminateSupportFacadesQueue::class,
    'Redirect' => IlluminateSupportFacadesRedirect::class,
    'Redis' => IlluminateSupportFacadesRedis::class,
    'Request' => IlluminateSupportFacadesRequest::class,
    'Response' => IlluminateSupportFacadesResponse::class,
    'Route' => IlluminateSupportFacadesRoute::class,
    'Schema' => IlluminateSupportFacadesSchema::class,
    'Session' => IlluminateSupportFacadesSession::class,
    'Storage' => IlluminateSupportFacadesStorage::class,
    'URL' => IlluminateSupportFacadesURL::class,
    'Validator' => IlluminateSupportFacadesValidator::class,
    'View' => IlluminateSupportFacadesView::class,

],

];

Спасибо заранее 🙂

1 ответ

  1. Из-за того, как это Traitработает, вы можете вызвать его в любое время на любой модели, которая имеет существующий рейтинг. Если рейтинг не существует, он вернется null. Вы можете создать ratingв вашем контроллере, что совершенно нормально.

    Так, внутри вида, вы можете позвонить:

    {{ $post->averageRating() }} 
    

    и он вернет вам тоaverageRating, за что конкретный пост.

    Вашу модель необходимо реализовать на Ratingableзаводе.

    class Post extends Model implements Ratingable
    

    В настоящее время вы реализуете `рейтинг, который является неправильным.