Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

403 (Forbidden) on axios post. Laravel 5.7

Tags:

laravel

I'm trying to perform a post request with axios on a vuejs component and it throws an 403 forbidden error. This is my javascript code for the post request:

createMessage() {
            axios.post('/mensajes/guardar', {
                subject: this.subject,
                username: this.username,
                content: this.editorContent
            })
            .then((res) => {
                this.formProcessed = true
                this.swalMixin('success', '¡Mensaje enviado!')
                setTimeout(() => { window.location = '/mensajes' }, 3000)
            })
            .catch((err) => {
                let errors = err.response.data.errors
                let firstError = Object.keys(errors)[0]
                let message = errors[firstError][0]
                this.swalMixin('error', message)
            })
        }

The controller's fuction that handles it:

public function store(MessageStoreRequest $request)
    {
        $recipient = User::where('username', $request->username)->firstOrFail();

        $message = Message::create([
            'sender_id' => Auth::id(),
            'recipient_id' => $recipient->id,
            'subject' => $request->title,
            'content' => $request->content,
        ]);

        return response()->json([
            'message' => 'success'
        ], 200);
    }

My route group for the message model:

Route::prefix('mensajes')->middleware(['auth', 'verified'])->group(function () {
    Route::get('/', 'MessageController@index')->name('message.index');
    Route::get('/ver/{id}', 'MessageController@show')->name('message.show');
    Route::get('/crear', 'MessageController@create')->name('message.create')->middleware('can:create,App\Message');
    Route::post('/guardar', 'MessageController@store')->name('message.store')->middleware('can:create,App\Message');
});

I've created a custom request to handle the validation:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MessageStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'subject' => 'required|min:12',
            'username' => 'required|',
            'content' => 'required|min:37'
        ];
    }

    /**
     *  Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            'subject.required' => 'El asunto es obligatorio.',
            'subject.min' => 'El asunto debe contener al menos 10 caracteres.',
            'username.required' => 'El destinatario es obligatorio.',
            'content.required' => 'El contenido del mensaje no puede estar vacío.',
            'content.min' => 'El contenido del mensaje debe ser de al menos 30 caracteres.'
        ];
    }

    /**
     *  Filters to be applied to the input.
     *
     * @return array
     */
    public function filters()
    {
        return [
            'subject' => 'trim',
            'username' => 'trim',
            'content' => 'trim'
        ];
    }
}

And there is this policy for the Message model:

/**
     * Determine whether the user can create messages.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return $user->hasAccess(['create-message']);
    }

I can't find the problem. I've been working like this with other models and this is the first one that throws this error.

like image 768
enbermudas Avatar asked Oct 13 '25 05:10

enbermudas


1 Answers

Lets change authorize() function in your customized request to return true instead of return false.

This function is used to allow or disallow access based on permisions.

like image 68
nyu.exe Avatar answered Oct 15 '25 16:10

nyu.exe