nicolassiuol
nicolassiuol

Reputation: 83

Laravel 4.2 create a view count on a Post

Actually I need to implement a counter on a post view.
My structure of table Advertissements is

Id, Title, Descritpion, Content, view_count, visited_date, Ip

I tried to use an event but it's not the best practice I think. I don't know where to place my code.

public function show($slug) {
    $advert = Advertissement::where('slug', $slug)->firstOrFail();
    $author = $advert->user;

    $socials = Social::all();

    $catAdvert = AdvertCategory::with(['advertissements' => function($query){
        $query->orderBy('created_at', 'DESC')->get();
    }]);

    //Event problem here
    Event::fire('advertissements.view', $advert);

    return View::make('advertissements.show', compact('advert', 'author', 'catAdvert', 'socials'));
}

Upvotes: 2

Views: 882

Answers (1)

phaberest
phaberest

Reputation: 3220

To fire the event

Refer to the official documentation.

The Laravel Event class provides a simple observer implementation, allowing you to subscribe and listen for events in your application.

In your code you're firing an event that is not registered anywhere.

First, you need to pass data as an array in the firing process:

Event::fire('advertissements.view', array($advert));

Second, set the listener. It could be anywhere in your executed code, I usually put it in the app/routes.php file (others do it in app/start/global.php or in a composer autoloaded file...it's up to you):

Event::listen('advertissements.view', function($advert) {
    // Do what you want to handle the event
});

PS: FYI this is the way to handle events in Laravel 4.x, in Laravel 5 it has changed a bit. Taylor has improved the process, adding artisan command to help making and setting events. Have a look to the Laravel 5 events docs

For your counter

Create a model Counter

class Counter extends Eloquent {

    protected $table = 'counters';

    public function advertissement()
    {
        return $this->belongsTo('Advertissement');
    {
}

In your Advertissement model add

public function counter()
{
    return $this->hasOne('Counter');
{

In the migration for the Counter add an unsigned integer for advertissement_id and another unsegned integer for views, then in the listener use:

Event::listen('advertissements.view', function($advert) {
    $counter = new Counter();
    $counter->views = $advert->counter()->views++;
    $advert->counter()->save($counter);
});

Not tested (I don't have a working 4.2 on my machine right now), but should work.

Upvotes: 1

Related Questions