Retrieving the Slug from URL for function (Laravel 5)

1.7k views Asked by At

I'm making an App where a group is created by a user. This user can go to the group page (automated unique slug is created for the groups).

My goal is for the member who created the group, to be able to make a invite code for that specific group.

Currently the code generator is hardcoded to create one for the group with id=8.

Here is the code:

public function createInviteCode()
    {
        $group = Group::find(8); // Group ID you want to manage
        $code = Invite::generateCode();
        $invite = $group->invites()->create([
            'code' => $code,
            'expires_at' => Carbon::now()->addDays(7) // invite expires in 7 days
        ]);

        return redirect()->back();
    } 

The code is generated on through a submit button on my showgroup.blade.php:

{!! Form::open(['route' => 'invite.create']) !!}
{!! Form::submit('Generate invite code', ['class' =>  'btn btn-primary']) !!}
{!! Form::close() !!}

What I am trying to do, is retrieve the slug that I'm surfing to, to show this group:

function to retrieve the slug:

public function search()
{
    $group = Group::whereSlug($slug)->first();

    return view('pages.groups.showgroup')->withSlug($group);
}

Also these are my Routes.php:

$router->post('invites', ['as' => 'invite.create', 'uses' => 'GroupController@createInviteCode']);
$router->get('group/{slug}', ['as' => 'group.search', 'uses' => 'GroupController@search']);

So a small recap: Currently I'm simply creating a invite code for the group with ID=8. What I want to do is change my function so it creates a invite code for the group that I'm surfing to (aka through the slug)

How do I code this exactly?

1

There are 1 answers

0
Pex On BEST ANSWER

Fixed it:

Route:

$router->post('invites/{slug}', ['as' => 'invite.create', 'uses' => 'GroupController@createInviteCode']);

My form:

{!! Form::open(['route' => ['invite.create', $group->slug]]) !!}
{!! Form::submit('Generate invite code', ['class' =>  'btn btn-primary']) !!}
{!! Form::close() !!}

The function:

public function createInviteCode($slug)
{
    $group = Group::where('slug', $slug)->firstOrFail();

    // ...
}