3

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: enter image description here

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: enter image description here

Otto
  • 663
  • 3
  • 17
  • 33
  • 1
    Can you show how you are making a post request – karmendra Aug 08 '18 at 12:16
  • @karmendra I added the post request, it is done from vuex with axios. I also added the error I receive when I send out that post request. – Otto Aug 08 '18 at 12:22
  • 1
    Why are you treating a post request like a get request? `axios.post('/sendmessage/'+receive_id+'/'+message` send the receive_id and message as post parameters `axios.post('/sendmessage', { id: receive_id, message: message })` – Tschallacka Aug 08 '18 at 12:25
  • @Tschallacka The `axios.post('/sendmessage/'+receive_id+'/'+message` example works (at least to my knowledge), I've done post requests in that fashion that work. My guess is the error is somewhere on the controller side. – Otto Aug 08 '18 at 12:30
  • 1
    I'm not saying it doesn't work. I'm saying you're abusing the post method as a get method. Just send those parameters as post variables. That way you won't hit the 2048 character limit internet explorer has for example. – Tschallacka Aug 08 '18 at 12:32
  • @Tschallacka Oh okay, cool I'll try to fix that too then. Thanks – Otto Aug 08 '18 at 12:33
  • @Tschallacka Now I'm getting the error `app.js:26133 POST http://beam.local/sendmessage 404 (Not Found)` (I'm aware the url is different, but if i change the url, I get the same error as I've shown above). – Otto Aug 08 '18 at 12:35
  • `@csrf` not used? – Tpojka Aug 08 '18 at 12:42
  • 1
    Yea, the url with the error will remain, you're just sending the data in a better way. also, you'll have to get `$receive_id = post('id'), $message = post('message')` now instead of as arguments. In chrome, open up the network panel, click xhr, send the request, click the red request, then click response tab. and read the resonse, see if there's an error code in the raw response – Tschallacka Aug 08 '18 at 12:43
  • Can you please also provide the entire routes file instead of the two single routes? – IlGala Aug 08 '18 at 12:46
  • @IlGala I added that entire file as well! – Otto Aug 08 '18 at 12:56
  • @Tschallacka Ok I made changes and ill show them above in the post, "message": "Call to undefined function App\\Http\\Controllers\\post()", is what i get when i check there. However check how I changed my controller, I don't think it completely understood what you asked. – Otto Aug 08 '18 at 12:57
  • 1
    oh yea, sorry, got laravel and octobercms mixed up, you'll want to do `$request->input('variable_name');` also you're `$messages->fill($request->all());` and then manually filling the object. the `$request->all()` filling might end up setting variables that are not columns in the database if you haven't guarded everything. – Tschallacka Aug 08 '18 at 13:00
  • Its making progress, but now I get this error: `"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))"` Does that have something to do with guarding? It is trying to fill the database with `updated_at` which isn't even in the table nor in my model. – Otto Aug 08 '18 at 13:04
  • 1
    yea, your table for the Messages model doesn't have a column updated_at and created_at. You probaly forgot a `$schema->timestamps();` in your migration file. The timestamps are a standard part of laravel models. If you don't want them you'll need to define `public $timestamps = false;` in your Messages model. https://stackoverflow.com/questions/19937565/disable-laravels-eloquent-timestamps – Tschallacka Aug 08 '18 at 13:07
  • @Tschallacka Ok I feel like an idiot and maybe not I'm starting to remember I'm fairly new to laravel, my migrations don't contain anything except a create_users_table.php (that someone else put in there).. Am I suppose to create a migration file for every item I want to add to a certain table? (Just saw the rest of your comment, if I turn off $timestamps in my model it works!!!! Thank you sir.. this has taken days to try to figure out.) – Otto Aug 08 '18 at 13:12
  • 1
    The migration files are useful when you wish to move from your development pc to your production server so you don't have to manually re-create every single table you have defined and they make it easy to update your system by adding extra fields to tables or defining extra tables. That's why it's also called a "Migration" file. – Tschallacka Aug 08 '18 at 13:16

1 Answers1

5

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

Tschallacka
  • 27,901
  • 14
  • 88
  • 133