Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ifrit's avatar
Level 2

Getting author to view correct story in laravel

I'm using Laravel 7 and I'm trying to create a site where the user can login if they have a token. I seem to have that almost working in that if you don't have a token you can't access the page and if you put in a token that isn't in the database then it throws out an error.

The problem I'm having is that a user can still view a page they not meant to. For example I have Story 1 and Story 2, Author 1 can view both Story 1 and 2, but Author 2 can only view Story 2.

The issue is that Author 2 can view both Story 1 and Story 2, which is wrong they only supposed to see Story 2.

I wanted to use middleware for this but I kind of hit a brick wall and not sure what next to do.

My tables

Story Table
id | title
1  | Story 1
2  | Story 2


Author Table
id | name
1  | Author 1
2  | Author 2

author_story table
id | author_id | story_id
1  |    1      |    1
2  |    1      |    2
3  |    2      |    2

My Story.php

protected $fillable = ['title'];

public function authors()
{
    return $this->belongsToMany('App\Author');
}

My Author.php

protected $fillable = ['name'];

public function stories()
{
    return $this->belongsToMany('App\Story');
}

My ViewStory.php (middleware)

if(Auth::check())
{
    return $next($request);
}else{
    abort(401);
}
0 likes
4 replies
Ifrit's avatar
Level 2

@mvd - I will check the link out, but what do you mean by extend ViewStory.php?

guybrush_threepwood's avatar

You need some kind of relationship between an Author and it's corresponding User.

That way, you can check if the logged-in user's ID corresponds to any of the story's authors/users.

mvd's avatar

@ifrit

I will check the link out, but what do you mean by extend ViewStory.php?

In your ViewStory.php also do check if this user can see the story

if(Auth::check())
{
    if (!here_a_function_and_return_a_boolean_to_check_if_this_user_can_see_this_story) {
        abort(401);
    }
    
    return $next($request);
}else{
    abort(401);
}

Please or to participate in this conversation.