如何检索输入字段

时间:2015-02-05 13:35:37

标签: laravel laravel-5

如何获取更新任务的输入字段?当试图         dd(Request::input('task'));我得到“非静态方法Illuminate \ Http \ Request :: input()不应该静态调用,假设$ this来自不兼容的上下文”

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Task;
use Illuminate\Http\Request;

class TaskController extends Controller {

public function update($id)
{
    dd(Request::input('task'));
    $task = Task::findOrFail($id);
    $task->title = Request::input('task');
    $task->save();
    return Redirect::to('tasks');
}

编辑视图(工作正常)

{!! Form::model($task, array('url' => 'tasks/'.$task->id, 'method' => 'PATCH')) 
    !!}
    {!! Form::text('task', $task->task, array('class' => 'form-control')) !!}
    {!! Form::submit('Edit', array('class' => 'btn btn-default')) !!}
    {!! Form::close() !!}

2 个答案:

答案 0 :(得分:17)

您导入了错误的Request

要使用Request facade ,您必须执行以下操作:

use Illuminate\Support\Facades\Request

或者只是别名:

use Request

你也可以像这样使用依赖注入:

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Task;
use Illuminate\Http\Request;

class TaskController extends Controller {

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function update($id){
        $task = Task::findOrFail($id);
        $task->title = $this->request->input('task');
        $task->save();
        return Redirect::to('tasks');
    }
}

或者只对那一种方法使用DI:

public function update(Request $request, $id){
    $task = Task::findOrFail($id);
    $task->title = $request->input('task');
    $task->save();
    return Redirect::to('tasks');
}

答案 1 :(得分:10)

您应该使用依赖注入:

use Illuminate\Http\Request;

...

public function update(Request $request, $id)
{
    //
    $task->title = $request->input('task');
    //
}

有关详细信息,请参阅文档:http://laravel.com/docs/5.0/controllers#dependency-injection-and-controllers