Asked  9 Months ago    Answers:  5   Viewed   52 times

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

    use IlluminateHttpRequest;
    use AppModelsMessages;
    use AppUser;
    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

 Answers

65

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

Wednesday, March 31, 2021
 
Sagar
answered 9 Months ago
18

I solved this issue using this aswer. I've just went in my AppServiceProvider and put into boot method:

Blade::setEchoFormat('e(utf8_encode(%s))');

I don't know if this is the correct way to do it, but it works for me.

Friday, July 30, 2021
 
laurent
answered 4 Months ago
66

This is the rule that need to apply. Tested with sample data and it works as desired.

use IlluminateValidationRule;

$playlist_id = request('playlist_id');

$rules = [
    'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
        $query->where('playlist_id', $playlist_id);
    })
];

Sample condition

DB data
song_id     playlist_id
2           34
3           34

Request data
song_id     playlist_id     validation
2           34              fail
3           34              fail
4           34              success
2           35              success
3           35              success

Sample test code

$data = [
    'song_id' => 2,
    'playlist_id' => 34,
];

$playlist_id = $data['playlist_id'];

$validator = Validator::make($data, [
    'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
        $query->where('playlist_id', $playlist_id);
    })
]);

if ($validator->fails()) {
    // handle failed validation
}
Friday, August 20, 2021
 
shwabob
answered 4 Months ago
18

Use required_with or required_if

required_with:foo,bar

The field under validation must be present and not empty only if any of the other specified fields are present.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_with:has_login,on',
];

--

required_if:anotherfield,value

The field under validation must be present and not empty if the anotherfield field is equal to any value.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_if:has_login,on',
];

--

https://laravel.com/docs/5.2/validation

--

Also, if the checkbox has_login is not checked, it will not send as part of the form submission

Thursday, September 30, 2021
 
Bitmap
answered 2 Months ago
75

You can't provide a value for an interval like that. You need to multiple the parameter value with your interval base unit:

"select * from orders 
where created_date  < clock_timestamp() - (interval '1' day) * :days"

As you are dealing with days, you can simplify that to:

"select * from orders 
where created_date  < clock_timestamp() - :days"

Another option is the make_interval() function. You can pass multiple parameters for different units.

"select * from orders 
where created_date  < clock_timestamp() - make_interval(days => :days)"

The notation days => ... is a named parameter for a function call. If the variable represents hours, you could use make_interval(hours => ..)

Thursday, November 4, 2021
 
Angolao
answered 4 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share