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

laden's avatar
Level 1

Need help fetching the last segment of my url

I am trying to figure out how I can fetch the last segment of my url in my store function, and need some help figuring out what I am doing wrong.

its a form where I use a Pay With Stripe button as the submit button. This is what I am trying to use:

$courseId = request()->segment(count(request()->segments()));

The problem with this is that it ends up fetching the last segment of the url in the route for the store function. so when I am in the form, the url is: "/enrollmentprivate/course/1" and the url of the route is "/charge", witch is what I end up with instead of the "1".

This is the relevant part of the store function :

$courseId = request()->segment(count(request()->segments()));
$price = Course::where('kursId', $courseId)->value('pris'); 

Stripe::setApiKey(env('STRIPE_SECRET_KEY'));

$customer = Customer::create(array(
    'email' => $request->stripeEmail,
    'source'  => $request->stripeToken
));

$charge = Charge::create(array(
    'customer' => $customer->id,
    'amount'   => $paymentPrice,
    'currency' => 'nok'
));
return redirect()->back();

This is the script for the Stripe button, dont really know if this is relevant:

<script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="{{ env('STRIPE_PUB_KEY') }}"
    data-amount="{{ $course->pris }}"
    data-label="Betal med kort"
    data-name="Stripe"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-currency="nok">
</script> 

any help figuring out what I am doing wrong here would be very much appreciated!

0 likes
2 replies
arthurvillar's avatar
Level 9

I always avoid solutions that make me grab a piece of a string from some place and reuse it somewhere else. These "hacky" solutions always end up creating more problems than they solve.

Can you have a hidden input in your form? If yes, you can add this to your form

<input type="hidden" name"course_id" value="{{$course->id}}">

The value of this input will be part of the $request variable.

1 like
laden's avatar
Level 1

Thank you sir! this for sure solves my issue and is a much better solution :)

1 like

Please or to participate in this conversation.