Vue js Laravel axios POST 500 Internal Server Error - laravel

I've just created laravel Vuejs Project using Axios for call API.
Get Api is working well but When I am going to post my data, getting Internal server error.
I am using Resourse for for controller.
I just Create Api and get data by This:
axios.get("http://localhost:8080/vuelaravel/tasks")
.then(response =>{this.tasks = response.data})
.catch(error => console.log(error.response));
vuelaravel is my project name.
Its working well. But when i am trying to post data into my database its shown 500 internal error.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Todo;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class TodoController extends Controller
{
public function index()
{
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return request()->json(200,$tasks);
}
public function create()
{
//
}
public function store(Request $request)
{
$todo=Todo::create($request->all());
if($todo){
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return request()->json(200,$tasks);
}
}
public function show(Todo $todo)
{
//
}
public function edit(Todo $todo)
{
//
}
public function update(Request $request, Todo $todo)
{
//
}
public function destroy(Todo $todo)
{
//
}
}
And My ADD.Vue
<template>
<div>
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" name="name" v-model="name" id="name" placeholder="Title Name" class="form-control" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" #click="addRecord">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
name:'',
}
},
methods:{
addRecord(){
axios.post("http://localhost:8080/vuelaravel/tasks",{
'name': this.name,
})
.then(data => console.log(data))
.catch(error => console.log(error))
}
}
}
</script>
<style scoped>
</style>
This is The Error:
app.js:285 POST http://localhost:8080/vuelaravel/tasks 500 (Internal Server Error)
at createError (app.js:699)
at settle (app.js:960)
at XMLHttpRequest.handleLoad (app.js:168)
I am using my csrf in Welcome.blade.php
<meta name="csrf-token" content="{{csrf_token()}}">
Get my data by This Api:
created(){
axios.get("http://localhost:8080/vuelaravel/tasks")
.then(response =>{this.tasks = response.data})
.catch(error => console.log(error.response));
}

Since you are using the method create in your model, please make sure you had mass assigned in your model by putting this code above.
protected $guarded = [];
please read this docs soruce

Try this
response($tasks) method
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return response($tasks);

Related

Laravel Livewire Typed property must not be accessed before initialization on form submission

New to livewire, and trying to convert an existing form to a livewire component.
When I submit the form, I'm getting this error:
Typed property App\Http\Livewire\LocationInfo::$location must not be accessed before initialization
I'm not sure how to make this work, or what I'm doing wrong. I was expecting that the save() method would know about $this->location, but maybe I'm misunderstanding something. Can't seem to find anything different in the docs from what I'm doing. I've also looked through other questions with the same error and not finding an answer.
I can move the Log statement to the mount method or the render method and it will log the correct info. I don't understand why it's not available to the save() method.
Here's my livewire component:
class LocationInfo extends Component
{
public Object $states;
public Location $location;
protected $rules = [
'location.name' => ['required', 'string', 'max:150'],
...
];
public function mount(Location $location)
{
$this->location = $location;
$this->states = USState::all();
}
public function render()
{
return view('livewire.location-info');
}
public function save()
{
Log::debug($this->location);
}
}
and here's my form:
<div class="modal fade" id="location_info_modal" tabindex="-1" aria-labelledby="location_info_modal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<form wire:submit.prevent="save" class="" id="location_info_form" method="POST" action="/locations/{{ $location->id }}">
<div class="modal-content">
<div class="modal-header d-flex justify-content-between">
<div id="modal_header" class="d-flex justify-content-start align-items-center">
<h5 class="modal-title pe-3">Edit Location Info</h5>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="btn-close"></button>
</div>
<div class="modal-body">
<div class="row">
#csrf
<div class="mb-3 col-md-8">
<label for="name" class="form-label">Location Name</label>
<input wire:model="location.name" type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ $location->name ?? '' }}" data-inputmask-regex="[A-Za-z0-9#.,''-() &]+">
#error('location.name') <span class="error">{{ $message }}</span> #enderror
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary save_btn" id="location_info_save" disabled>Save</button>
</div>
</div>
</form>
</div>
</div>
and here's my route:
Route::post('/locations/{id}', [LocationInfo::class, 'save'])
->middleware('auth');
I had this error before to me it was the typed property try to remove it like:
public $location;
public function mount(Location $location)
{
$this->location = $location;
}
or remove the one in the mount:
public Location $location;
public function mount()
{
$this->location = new Location();
}

How to solve Laravel Post Error 403 with ajax?

I want to insert some record into database table which is using server side mode. Im using laravel 8, php version 8.0.13, database mysql.
This is my Route
use App\Http\Controllers\JabatanController;
Route::resource('jabatan', JabatanController::class, [
'names' => [
'index' => 'jabatan.list',
'store' => 'jabatan.store',
]]);
//dd($request->all());
My view
<button type="button" id="tambah-jabatan" class="btn btn-primary float-right" data-toggle="modal" data-target="#modal_tambah">
Tambah Jabatan
</button>
<!-- Modal -->
<div class="modal fade" id="modal_tambah" tabindex="-1" role="dialog" aria-labelledby="modalTambahLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalTambahLabel">Tambah Data Jabatan</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- mb -->
<div class=" mb-3">
<label for="jabatan">Jabatan</label>
<input type="text" name="jabatan" class="form-control" id="jabatan" placeholder="Masukkan Jabatan disini" value="" required>
</div>
<!-- /mb -->
</div>
<div class="modal-footer">
<button type="button" id="close" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="save-jabatan" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
My Controllers
public function store(StoreJabatanRequest $request)
{
$data = Jabatan::updateOrCreate([
'jabatan' => $request->jabatan,
]);
return response()->json($data);
}
My Model
class Jabatan extends Model
{
use HasFactory;
protected $table = "jabatans";
protected $fillable = [
'jabatan'
];
}
some ajax script in my main view
<script>
$('#save-jabatan').on('click', function() {
$.ajax({
url: "{{route('jabatan.store')}}",
type: "post",
data: {
jabatan: $('#jabatan').val(),
"_token": "{{csrf_token()}}"
},
success: function(res) {
console.log(res.data);
alert(res.text)
$('#close').click()
$('#tb_jabatan').DataTable().ajax.reload()
},
error: function(xhr) {
alert(xhr.responseJSON.text)
}
})
})
</script>
and when im check on inspect i got this error
POST http://localhost:8000/jabatan 403 (Forbidden)
there's any suggestion?
Ok, so in my case the problem is on my App\Http\Request\StoreJabatanRequest.php
class StoreJabatanRequest extends FormRequest;
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'jabatan' => 'required'
];
}

Ajax not displaying error message itself, box only

For some reason AJAX is not passing the error message. Whatever I try to submit in my form, I get red line (error message style) but without error message init, which makes hard for me to debug. Any ideas what is causing error message not to be displayed?
My AJAX function, pointing to store method in TicketCategory controller:
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/ticket-category/store',
data: {
name: $("#frmAddTicketCategory input[name=name]").val(),
},
dataType: 'json',
$('#frmAddTicketCategory').trigger("reset");
$("#frmAddTicketCategory .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-ticket-category-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-ticket-category-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
My view:
<div class="modal fade" id="addTicketCategoryModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTicketCategory">
<div class="modal-header">
<h4 class="modal-title">
Add New Task
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-ticket-category-errors">
</ul>
</div>
<div class="form-group">
<label>
Name
</label>
<input class="form-control" id="name" name="name" type="text">
</input>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="Cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
Add New Task
</button>
</input>
</div>
</form>
</div>
</div>
</div>
Controller:
public function create()
{
return view('ticket_category/ticket_cat',[
'tickets' => TicketCategory::all()
]);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required'
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$ticket_category = TicketCategory::create([$request->name]);
return response()->json([
'error' => false,
'ticket_category' => $ticket_category,
], 200);
}
see the error issue
I think value is an array of errors for a field that is why you are not able to display the errors. Try this
$('#add-ticket-category-errors').append('<li>' + value[0] + '</li>')

Laravel Vue js Response Result not updating after axios call

I have vue component.After axios response counter not updating on popup. showInterest function is called on created method.
<template>
<span class="interested-button">
<a data-toggle="modal" data-target="#buyModel" #click="showInterest(idea_id, owner_id)">
<i class="fa fa-usd" aria-hidden="true"></i> Interested to buy?
</a>
<div
class="modal fade"
id="buyModel"
tabindex="-1"
role="dialog"
aria-labelledby="buyModelLabel"
aria-hidden="true"
>
<div class="modal-dialog" role="ideabuy">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="buyModelLabel">How much you are willing to spend?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{{ sharedPriceCount }}
<template v-if="sharedPriceCount == 0">
<form #submit.prevent="saveIdeaPrice">
<div class="modal-body">
<div class="form-group">
<input type="text" v-model="price" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
</template>
<template v-else>
<div class="modal-body">
<div class="form-group">You have already shown interest for this Idea.</div>
</div>
</template>
</div>
</div>
</div>
</span>
</template>
<script>
import mixins from "../mixins";
export default {
name: "buyProduct",
mixins: [mixins],
props: ["input_name", "idea_id", "owner_id"],
data() {
return {
result: [],
loading: false,
price: 0,
sharedPriceCount: 0
};
},
created() {},
mounted() {},
methods: {
saveIdeaPrice() {
axios
.post("/idea-buy-price", {
id: this.idea_id,
owner: this.owner_id,
price: this.price
})
.then(res => {
this.loading = false;
})
.catch(res => (this.loading = false));
},
showInterest(idea_id, owner_id) {
let _self = this;
axios
.get("/idea-buy-price/" + idea_id + "/" + owner_id)
.then(
function(response) {
_self.result = JSON.stringify(response.data.data);
_self.sharedPriceCount = response.data.data.length;
console.log(_self.sharedPriceCount);
_self.loading = false;
}.bind(_self)
)
.catch(
function(error) {
_self.loading = false;
}.bind(_self)
);
},
updateCall() {}
}
};
</script>
I am getting Array data through api call.but on popup its not working properly.I want to update this.sharedPriceCount when popup open.to show the popup content.without refreshing page.
Anyone can help me on this?
If result and loading are updated then please disregard following:
I had trouble with this. within function in axios call.
Solved it by defining
var _self = this;
before axios call and using _self within response function

Components. Send request with file via vue.http.post()

I have vuejs2 component on page (single file component). It's a simple bootstrap modal window with one file input. I only need to upload one file (no mutlifile upload or etc.)
What is in file:
<template>
<div class="modal fade" id="upload-file-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Upload file</h4>
</div>
<form id="app-file-upload-form" name="appFileUploadForm" #submit.prevent="uploadAppFile" novalidate enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="app-file-fileinput">File</label>
<input type="file" name="file" id="app-file-fileinput" class="form-control" v-el="file" #change="attachFile">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
</div>
</div>
</div>
<script>
export default {
data() {
return {
file: ''
}
},
methods: {
attachFile(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.file = files[0];
},
uploadAppFile() {
console.log(this.file);
Vue.http.post('/api/v1/apps/' + this.appId + '/files', { file: this.file}).then((response) => {
console.log(response);
}, (response) => {
console.log(response);
});
}
}
}
So i have laravel controller for handle it.
public function upload(Request $request)
{
$attachedFile = $request->file;
return response()->json($request->all());
}
I put return response->json() for kinda debug this. When i attach file, file attaching to component(model?) field and not empty. But when vue.http.post happening the file comes to empty object.
First is console.log(file)
Second is server response.
I also tried with FormData()... it didn't work.
ps: i cut version field from code.
After few more times with formdata i got file upload working. Just put variable inside method.
uploadAppFile() {
let data = new FormData();
data.append('file', this.file);
Vue.http.post('/api/v1/apps/' + this.appId + '/files', data).then((response) => {});
}

Resources