Laravel Post Controller不工作(Symfony \ Component ...) [英] Laravel Post Controller not working (Symfony \ Component...)

查看:76
本文介绍了Laravel Post Controller不工作(Symfony \ Component ...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的整个laravel控制器无法正常工作.当我对此控制器index()进行get请求时,它可以完美地工作.但是,当我向此控制器发出post请求到store()时,它不起作用.

My entire laravel controller isn't working. When I do a get request to this controller index() it works perfectly. But when I do a post request to this controller to store(), it doesn't work.

当我尝试排除故障时,我开始注释掉代码或使用dd().然后,当我注释掉整个控制器时,很快就注意到该错误没有改变. (或者当我dd($ user_id)没变的时候.)

When I was trying to trouble shoot I started commenting out code or using dd(). Then quickly noticed when I commented out my entire controller it made no change on the error. (or when I dd($user_id) nothing changed).

我的错误:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message

路由文件:

<?php

Route::get('/', function () {
    return view('welcome');
});


Route::get('/test','TestController@index');

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home')->middleware('auth');
Route::get('/inspirations','InspirationsController@index')->middleware('auth');
Route::get('/spaces','SpacesController@index');
Route::get('/user/{id}','UserController@index'); // other profiles
Route::get('/user','UserController@myprofile'); // my profile
Route::get('/mymessages','MessagesController@index'); // messages


Route::get('/testauth/', function()
{
    var_dump(Auth::user()->id);
    // your code here
});

Route::post('/pins/{inspiration_id}/{room_id}','PinsController@store')->middleware('auth');
Route::post('/editRoom/{id}/{name}/{description}','RoomsController@update');
// how i was doing it --> Route::post('/sendmessage/{receive_id}/{message}','MessagesController@store');
Route::post('/sendmessage','MessagesController@store');


Auth::routes();

我的控制器:

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Models\Messages;
    use App\User;
    use Auth;

        class MessagesController extends Controller
        {
            public function index()
            {
                // We need to be able to see each user that has corresponded with this particular user. And only display them once on their users list.
                // Hence we made a 'correspondence_id' so we can filter that later on in vue.

                // Grab current user.
                $user_id = Auth::user()->id;

                // Grab all messages related to this user.
                $messages = Messages::where('send_id', $user_id)->orWhere('receive_id', $user_id)->get();

                foreach($messages as $message) {

                    // for each message we want to grab the first and last name of the person we received or send the message to.
                    if($user_id == $message['send_id']) {
                        // User_id is my id, so we don't want that name.
                    } else {
                        // We want to grab their name.
                        $user = User::where('id', $message['send_id'])->first();

                        // Add this user to the message.
                        $message['firstname'] = $user['firstname'];
                        $message['lastname'] = $user['lastname'];
                        // Add profile_img url.
                        $message['profile_img'] = $user['profile_img'];
                        // Add id of user you are speaking to.
                        $message['correspondence_id'] = $message['send_id'];
                    }

                    if($user_id == $message['receive_id']) {
                        // User_id is my id, so we don't want that name.
                    } else {
                        // We want to grab their name.
                        $user = User::where('id', $message['receive_id'])->first();

                        // Add his first and last name to the message.
                        $message['firstname'] = $user['firstname'];
                        $message['lastname'] = $user['lastname'];

                        // This should have the image of the profile who is receiving the image (not the other user).
                        $currentUser = User::where('id', $message['send_id'])->first();
                        $message['profile_img'] = $currentUser['profile_img'];

                        // Add id of user speaking to you.
                        $message['correspondence_id'] = $message['receive_id'];

                    }

                }

                return compact('messages');

            }
    public function store(Request $request)
{
    $receive_id = post('id');
    $message = post('message');

    // Grab current user.
    $user_id = Auth::user()->id;

    $messages = new Messages();

    $messages->fill($request->all());

    $messages->send_id = $user_id;

    $messages->receive_id = $receive_id;

    $messages->message = $message;

    $messages->save();

    $text = "Message stored";

    return compact("text");

}

} 错误:

我的发帖请求是通过axios(vuex)完成的:

sendMessage({ commit }, payload){
        var receive_id = payload.receive_id;
        var message = payload.message;
        console.log(payload)

        axios.post('/sendmessage/'+receive_id+'/'+message, {
        }).then(function (response) {
            console.log(commit);
            console.log("success");
        }).catch((response) => {
            // Get the errors given from the backend
            let errorobject = response.response.data.errors;
            for (let key in errorobject) {
                if (errorobject.hasOwnProperty(key)) {
                    console.log(errorobject[key]);
                    this.backenderror = errorobject[key];
                }
            }
        })
    }

**对发布请求的更改(由Tschallacka提出)**

**Changes to post request (asked by Tschallacka) **

sendMessage({ commit }, payload){
        var receive_id = payload.receive_id;
        var message = payload.message;
        console.log(payload)

        axios.post('/sendmessage', { receive_id: receive_id, message: message
        }).then(function (response) {
                console.log(commit);
                console.log("success");
            }).catch((response) => {
                // Get the errors given from the backend
                let errorobject = response.response.data.errors;
                for (let key in errorobject) {
                    if (errorobject.hasOwnProperty(key)) {
                        console.log(errorobject[key]);
                        this.backenderror = errorobject[key];
                    }
                }
            })}

发布请求期间出错:

推荐答案

请勿将POST请求用作GET请求.浏览器可能会限制URL的长度.

Don't make use of a POST request as a GET request. You're likely to run into browser limitations of how long an URL may be.

axios.post('/sendmessage/'+receive_id+'/'+message, {

进入

axios.post('/sendmessage', { id: receive_id, message: message })

然后在您的控制器中更改

Then in your controller change

public function store(Request $request,$receive_id, $message)

public function store(Request $request)
{
    $receive_id = $request->input('id');
    $message = $request->input('message');

要排除其他错误,请打开开发控制台.按F12. 单击网络选项卡,然后选择XHR日志记录.

To trouble shoot any other errors, open your development console. Press F12. Click on the network tab and select XHR logging.

发出请求.它将显示为错误500请求.单击文件名(红色镶边),然后单击响应.查看错误并进行诊断.

Make the request. it will show up as a error 500 request. click on the filename(red in chrome) and click on response. Look at the error and diagnose it.

Chrome中的示例

以您的情况

消息":"SQLSTATE [42S22]:找不到列:1054"字段列表中的未知列"updated_at"(SQL:插入消息中(receive_id,message,send_id,updated_at,created_at))值(3,测试,1,2018-08-08 13:00:54,2018-08-08 13:00:54))"

"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into messages` (receive_id, message, send_id, updated_at, created_at) values (3, test, 1, 2018-08-08 13:00:54, 2018-08-08 13:00:54))"

$schema->timestamps()添加到您的迁移文件中,或在Messages模型中设置属性public $timestamps = false;

Either add the $schema->timestamps() to your migration file or set the property public $timestamps = false; in your Messages model

这篇关于Laravel Post Controller不工作(Symfony \ Component ...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆