0
votes

On my page events.index, I first display a list of events for the logged on user.

On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user.

I'm not sure what would be the best approach:

  • Set a session variable to keep the user_id value? Not sure how to do that with a form.
  • Submit the form with a get method (and get an ugly ?user_id=1 URL)
  • Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController@store'))

Not sure what would be a clean way to do this:

My route for events/index:

Route::get('events', [
'as' => 'event.index',
'uses' => 'EventsController@index'
]);

Events Controller

public function index()
{
    // How to get the $user_id value from form?

    if (empty($user_id)) 
    {
        $user_id = \Auth::user()->id;
    }

    $events = Event::where('events.user_id','=','$user_id');        
    $users  = User::all();

    return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}

View for index

{!! Form::open(['route' => 'events.index', 'method' => 'get']) !!}

    <select id="user_id" name="user_id">
    @foreach($users as $user)
        <option value="{{$user->id}}">{{$user->name}}</option>
    @endforeach
    </select>

{!! Form::submit('Show events for this user') !!}

{!! Form::close() !!}   


@foreach($events as $event)
     ...
@endforeach
1
I'd use option #2 as in my opinion this is the cleanest way: User #1 looks at events of User #2, so User #1 should be on an URL like ?user=2jakub_jo
You could just use javascript to do the filtering, unless you need the filter to be saved globally, e.g., select user A and then other pages will also filter by user A. In that case I would use an ajax post to save the user filter value and have all your queries filter by that if it's set.vonec
@jakub_jo not that its not clean, but it doesn't generate a pretty url.user3489502

1 Answers

1
votes

You can get the user_id from a Request object, you just need to inject it in the index method:

public function index(Request $request)
{
    $user_id = $request->get('user_id') ?: Auth::id();

    $events = Event::where('events.user_id','=','$user_id')->get();

    $users  = User::all();

    return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}