Jatz's avatar
Level 6

Update the url with the id before displaying page

I am new to Laravel and I need some help. I have a small application where an activity is created and I want to include the activity id in the url in the first instance. This is how it works. Click on a link that routes to 'activity/add'

Route::get('activity/add', 'ActivityController@create');

ActivityController

public function create()
    {
        $centreId = Auth::user()->centre_id;
        //Find an empty activity or start a new one with these details.
        $activity = Activity::firstOrCreate(['activity_date' => '2000-01-01', 'centre_id' => $centreId]);

        return view('activity.add', compact('activity'));
    }

The controller will create or find the row. The url will be activity/add and will display the activity form fine, but I would like the url to be "dynamically" changed to activity/123 and then display the activity form.

Essentially from here on out the user has a row on the database but they have not entered anything yet but it allows them to add an image or for me to create auto updating later etc.

Any suggestions would be great. TIA.

0 likes
2 replies
katifrantz's avatar
Level 6

Use a redirect to a defined route . Like this :


$activity = Activity::create();

return redirect()
        ->route('create-activity', ['id', $activity->id]);

And in your web.php:


Route::get('/create-activity/{id}', [

    'uses' => 'ActivityController@createActivity',
    'as'      => 'create-activity'
]);

Then the createActivity method can be as such :

public function createActivity($id)
{
    return view('activity.add')
            ->with('activity', Activity::find($id));
}

Please or to participate in this conversation.