首页 文章

在Laravel 5中的表单提交上重定向回同一页面(带变量)

提问于
浏览
0

在我的页面events.index上,我首先显示登录用户的事件列表 .

在我的索引页面上,我有一个带有选项/选择的表单,让用户选择并显示另一个用户的事件 . 当他提交该表单时,我希望我的索引函数(控制器)使用$ user_id值(来自表单)并再次显示events.index页面,但是对于所选用户的事件 .

我不确定什么是最好的方法:

  • 设置会话变量以保持user_id值?不知道如何使用表单 .

  • 使用get方法提交表单(得到一个丑陋的?user_id = 1 URL)

  • 更改我的索引路线以接受post方法(虽然我已经有了这个帖子/事件路线(通过Route :: post('events','EventsController@store'))

不确定什么是干净的方式来做到这一点:

我的事件/索引路线:

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

事件控制器

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]);
}

查看索引

{!! 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 回答

  • 1

    你可以从 Request 对象中获取 user_id ,你只需要在索引方法中注入它:

    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]);
    }
    

相关问题