调用POST

时间:2016-02-12 08:46:41

标签: php laravel post laravel-5 put

我是Laravel的新手,我尝试更新用户表中的记录,但是我得到了MethodNotAllowedHttpException,我已经尝试了所有内容,但没有任何效果。

UsersController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Users;

class UsersController extends Controller
{
    public function index()
    {
        $users = Users::all();
        return view('admin.users',compact('users'));
    }

    public function block(Request $request)
    {
        $user = Users::find($request->id);
        $user->blocked = 1;
        $user->save();

        return redirect()->action('UsersController@index'); 
    }
}

route.php

Route::get('/admin/users', 'UsersController@index');
Route::post('/admin/users/block',  'UsersController@block');

直到$user->blocked = 1;一切顺利。

UPDATE 我从这个jQuery方法访问控制器

$("#valdiate-user-block").click(function(){
    var data = {
        id: 2
    }
    $.ajax({
        url: "block",
        type:"POST",
        data: data,
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
    });

我没有提及它,因为我本地化了错误,当我从根访问控制器时我得到错误,当从jQuery访问它时我得到了

POST http://localhost:1303/admin/users/block 500 (Internal Server Error)

请帮帮我堆积!!

3 个答案:

答案 0 :(得分:1)

如果您想要更新,则必须使用public function block(User $user, Request $request) { $input = $request->all(); $input['blocked'] = 1; $user->update($input); return redirect()->action('UsersController@index'); } 考虑该方法和方法

POST

如果你想使用public function block(Request $request) { $input = $request->all(); $input['blocked'] = 1; User::create( $input ); return redirect()->action('UsersController@index'); } ,那么就这样做

MultiView

答案 1 :(得分:0)

而不是使用以下两行:

use Illuminate\Http\Request;
use App\Http\Requests; // seems this one also incorrect to me (Requests?)(Request !)

只需使用以下内容并查看:

use Request;

您的更新代码将是:

    namespace App\Http\Controllers;
    use Request;
    use App\Http\Controllers\Controller;
    use App\Users;
    use Illuminate\Support\Facades\Input;

    class UsersController extends Controller
    {
        public function index(){
            $users = Users::all();
            return view('admin.users',compact('users'));
        }

        public function block(){

            $inputData = Input::all(); // Reads all input array
            $your_id=   $inputData['id'];
            $user->blocked = 1;
            $user->save();

            return redirect()->action('UsersController@index');

        }
    }

答案 2 :(得分:0)

我修好了:)

我添加了public $timestamps = false; 在Users类

我删除了ajax调用中的类型

$.ajax({
url: "users/block/",
data: data,
success:function(data){
alert(data);
},error:function(){ 
alert("error!!!!");
}

Thanx求助:)