XHR 500 Internal Server Error when Posting Data using Vue in Laravel

Viewed 412

I'm having problem in storing data in laravel, what I have done is created a request for using php artisan make:request and add fillable to my Model then added the process to the Vue component.

I also add v-model="form.name" and @click="submit" to the button for the form process.

In the end I am getting this 505 internal server error

I have also added <meta name="csrf-token" content="{{ csrf_token() }}"> to my app.blade.php

Is there a way to fix this and post my data successfuly?

Vue:

<script>

export default {

    data(){
        return{
            form: {
                job_name: null,
                job_description: null,
                vacants: 0
            }
        }
    },
    methods: {
        submit(){
            axios.post('/job_postings', this.form)
            .then(function (response){
                console.log(response);
            })
            .catch(function (error){
                console.log(error);
            });
        }
    }
}
</script>

Controller:

   public function store(JobPostingRequest $jobPostingRequest, JobPosting $jobPosting)
    {
        $posting = $jobPosting::create($jobPostingRequest->all());
        return response()->json(['message' => 'Job Posting has been successfully saved', 'data' => $posting]);
    }

Requests:

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'job_name' => 'required',
        'job_description' => 'required',
        'vacants' => 'required'
    ];
}

Model:

class JobPosting extends Model
{
    use HasFactory;
    protected $fillable = [
        'job_name',
        'job_description',
        'vacants'
    ];
}

Routes/Web.php:

Route::resource('job_postings', JobPostingController::class);
1 Answers

You can get all values from your request with ->validated() method and create JobPosting from there.

use App\Models\JobPosting;

        if($posting = JobPosting::create($jobPostingRequest->validated())){
            return response()->json(['message' => 'Job Posting has been successfully saved', 'data' => $posting]);
        }

        return response()->json(['message' => 'Job posting failed.']);

Try this instead your store function.

Related