Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

Getting id value from url in controller and displaying values associated laravel

I'm trying to create a ticket management system with laravel jetstream and livewire. In the user page there's a table with all tickets that the user created. When the user clicks on the button to open one specific ticket, it should pass the id of the ticket and redirect to another page where it receives the data of that ticket he clicked, like title, message, etc..

The id is passed through the url, but my main problem is that whenever I try to display that data in the view, nothing shows, no errors either. I think that something might be wrong with my controller.

Here's my route:

Route::get('tickets.answers/{id}', [TicketsController::class, 'answers']);

The button to redirect to that specific ticket:

<a href="{{ url('tickets.answers' . '/'. $ticket->id ) }}" >    <x-jet-secondary-button >
                See Answer
</x-jet-secondary-button></a>

AnswersController:

  public function render(Request $request)
    {
        $tickets =  Ticket::where('id', $request->url('id'));
        
             
    return view('livewire.tickets.answers', [
        'tickets' => $tickets,
       
    ]);
    }

And how I'm trying to display in my blade:

@foreach($tickets as $key => $ticket)
<!-- This example requires Tailwind CSS v2.0+ -->
<div class="bg-white shadow overflow-hidden sm:rounded-lg">
    <div class="px-4 py-5 sm:px-6">
      <h3 class="text-lg leading-6 font-medium text-gray-900">
        Ticket no {{$ticket->id}} - {{$ticket->title}}
      </h3>
     
    </div>
</div>
    @endforeach
question from:https://stackoverflow.com/questions/66048906/getting-id-value-from-url-in-controller-and-displaying-values-associated-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your TicketsController you can fetch the id like this

public function answer(Request $request, int $id)
{
    // Use the find() method, instead of where(), when searching for the primary key
    $tickets =  Ticket::find($id);

    // .. more
        
}

In your routes files you specify an answer method, so use this in your TicketsController.

// See how to name a route
Route::get('tickets.answers/{id}', [TicketsController::class, 'answers'])->name('tickets.answers');

Then use the named route in your view like this:

<a href="{{ route('tickets.answers', ['id' => $ticket->id]) }}">

You can see a similar example in the Laravel docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...