Laravel Post Controller not working (Symfony \\ Co

2019-05-12 01:49发布

问题:

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.

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).

My error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message

Routes file:

<?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();

My controller:

    <?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");

}

} Error:

My post request is done via 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];
                }
            }
        })
    }

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

Error during post request:

回答1:

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.

turn

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

into

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

Then in your controller change

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

to

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

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

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.

example in chrome

In your case

"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))"

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