Cannot access id being passed in vue.js and laravel - laravel

I am having hard time inserting the values which is the id that is being passed from the form into the controller of my enrollment system. To achieve this I make use of vue.js and vue-resource library. In my all.js file I am gettting the correct id value when I console.log the id being passed. However, when passing it to the route address of my application I am getting 500 error. Also, upon debugging I' m getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'section_subject_id' cannot be null (SQL: insert into reservations. How can I solve this?
ReservationController.php
class ReservationController extends Controller
{
public function create($id)
{
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects'));
}
public function store(Request $request)
{
$subject = new Reservation();
$subject->section_subject_id = $request->input('id');
$subject->student_id = 1;
$subject->save();
}
}
all.js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#app-layout',
data: {
subject: {
id : ''
},
subjects: []
},
ready: function(){
},
methods:{
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', id, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}
}
});
form.blade.php
<body>
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id }} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>

Try formatting the data being sent like this: {id: this.id}
So your Vue addSubject Method looks like this:
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', {id: this.id}, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}

Related

How to showing data on table with datatables 'yajra'

I following this tutorial : How to route in Laravel DataTables
its so simple , but i cant do it . after i set my controller and my route and view , its not showing data and and table. in the table i have a button like'action' how i can take this comand to this button ?
can you check my faulth query
Route::get('user/show1', 'userController#show')->name('usershow1');
Route::get('user/show1-dt', 'userController#indexDataTables')->name('usershow1dt');
controller
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTables()
{
$pemeliharaan = Pemeliharaan::query();
// return DataTables::eloquent($pemeliharaan)->toJson();
return Datatables::of($pemeliharaan)->make(true);
}
and i have a view like this . the page number,search and pagination is showing at view ,but this data not showing. can you correctted this view ?
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>status</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
{{-- #php ---> before i suing datatables my view like that
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>
<td>{{ $i->created_at}}</td>
</tr>
#endforeach --}}
</tbody></table>
</div>
.
.
#endsection
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('usershow1dt') !!}',
columns: [
{ data: 'nama_alat', name: 'nama_alat'},
{ data: 'status', name: 'status'},
{ data: 'User Input', name: 'nama'},
{ data: 'Action', name: 'name'},//here my button
{ data: 'Tanggal', name: 'created_at'},
],
});
})
</script>
#endpush
Try This:
public function show() {
$pemeliharaan = Pemeliharaan::where('user','alat')->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}

Retrieve data using axios vue.js

I retrieve data using axios in methods created () like this:
data() {
return {
filterBox: false,
color: [],
sortBy: null,
productType: [],
products: null,
productcolors: null,
categories: null,
active_el: 0,
isActive: false,
categories: null,
inputSearch: '',
}
},
created() {
axios.get('/admin/product_index_vue').then(response => {
this.products = response.data.products.data;
this.productcolors = response.data.productcolors;
this.categories = response.data.categories;
console.log(this.products.length);
}).catch((error) => {
alert("ERROR !!");
});
},
when checking using console.log the data is there :
Vue DevTools :
but when trying to check the mounted () function I get empty data
what is the cause of this problem?
what I really want is to create a filter, but when using this function the data will not appear :
computed: {
filteredProduct: function () {
if (this.products.length > 0) {
return this.products.filter((item) => {
return (this.inputSearch.length === 0 || item.name.includes(this.inputSearch));
});
}
}
},
HTML CODE :
<tr v-for="product in filteredProduct">
<td style="width:20px;">{{product.id}}</td>
<td class="table-img-product">
<img class="img-fluid" alt="IMG">
</td>
<td> {{ product.name }}</td>
<td style="display:none">{{product.product_code}}</td>
<td>{{ product.base_color }}</td>
<td>{{ product.category }}</td>
<td>{{ product.price }}</td>
<td>{{ product.stock }}</td>
<td>{{ product.status }}</td>
<td>
<button type="button" name="button" v-on:click="deleteProduct(product.id,product.product_color_id)">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
RESULT
app.js:36719 [Vue warn]: Error in render: "TypeError: Cannot read
property 'length' of null"
found in
---> at resources\assets\js\components\products\Product_index.vue
what causes this function to not work and no detected product data?
This is because the computed property will potentially be calculated before the response has been returned.
If your data properties are going to be an array then I would suggest defining them as an array from the beginning. In the data object change the properties to something like e.g.
products: [],
productcolors: [],
Alternatively, you can add an additional check to your computed property method:
filteredProduct: function () {
if (!this.products) {
return [];
}
return this.products.filter((item) => {
return (this.inputSearch.length === 0 || item.name.includes(this.inputSearch));
});
}
this is axios response ont wording
mounted: {
let self = this
axios.get('/admin/product_index_vue').then(response=>{
self.products=response.data.products.data;
self.productcolors =response.data.productcolors;
self.categories=response.data.categories;
console.log(self.products.length);
}).catch((error)=>{
alert("ERROR !!");
});
},

405 Method Not Allowed - (1/1) MethodNotAllowedHttpException in Laravel 5

Hi i have this delete button which i really want to pass using ajax call. My problem is that when the delete button is clicked this is the error that i get
NetworkError: 405 Method Not Allowed and (1/1) MethodNotAllowedHttpException. This is my code below
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>
Im using the action('AddRecordController#destroy', $post['id']) since my AddRecordController is being generated. And my route is only this one
Route::resource('addRecord', 'AddRecordController');
My AddRecordController code below
public function destroy($id){
//
echo "Test";
echo $id;
$addRecord = Addrecord::find($id);
$addRecord->delete();
}
Can someone help me figured this thing out? Any help is muchly appreciated.
TIA.
You need to use the DELETE method. You can use form method spoofing to do this.
Try this:
<script type="text/javascript">
$(document).ready(function(){
$('.delete-block').on("click","a#deleteBtn", function() {
var x = confirm("Do you want to delete this?");
if(x){
var id = $(this).data("deleteid");
$.ajax({
type:"post",
url: $(this).data("href"),
data: {
id: id,
"_method": "delete"
},
success: function(data){
$("#deleteId"+ id).fadeOut('slow');
}
});
return true;
}else{
return false;
}
return false;
});
});
</script>
<tbody>
#foreach($datas as $post)
<tr class="delete-block" id="deleteId{{ $post['id'] }}">
<td>{{ $post['title']}}</td>
<td>{{ $post['post'] }} </td>
<td>{{ $post['comments'] }}</td>
<td>
Edit
Delete
</td>
</tr>
#endforeach
</tbody>

returning null when getting the values of the paramater of create method in laravel

I have a custom route that accepts parameter. Which is:
Route::get('reservation/{id}/create',
['as' => 'reservation.create', 'uses' => 'ReservationController#create'
]);
I have this variable protected $student_id. That id is being assigned to the parameter of the create method of ReservationController as seen below:
class ReservationController extends Controller
{
protected $student_id;
public function index()
{
return $this->student_id;
}
public function create($id)
{
$this->student_id = $id;
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects'));
}
public function store(Request $request)
{
$subject = new Reservation();
$subject->section_subject_id = $request->sectionSubjectId;
$subject->student_id = $this->student_id;
$subject->save();
}
}
When returning the $id parameter on the create method I get the exact id number. I also assigned that $id with the $student_id. But when assigning the $student_id on the store method I get null value. I know that I am doing wrong here, can someone please help me on this.
Okay, so let me add some information: In my url when using the reservation.create route I have this address localhost:8000/reservation/1/create
the number 1 in that url is the student id i want to get and assign to the student_id in my store method.
I also have this form view:
form.blade.php
<body>
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id }} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
At the same time I make us of vue.js and vue-resource
all.js
methods:{
addSubject: function(id){
this.$http({
url: 'http://localhost:8000/reservation',
data: { sectionSubjectId: id },
method: 'POST'
}).then(function(response) {
console.log('success');
},function (response){
console.log('failed');
});
}
}
You're trying to save variable in $this->student_id and use it later in another method. This is not how this works. The thing is these methods are used in different HTTP requests, so variable will not be kept.
You should pass this variable with from the reservation.form view to the store() method.
You can use Request object for that. In a view:
<input name="studentId" type="hidden">{{ $studentId }}</input>
And in controller:
$studentId = $request->get('studentId');
Or you can pass it as second parameter if you want to use it in a store() method.
public function store(Request $request, $studentId)
{
echo $studentId;

Convert eloquent relationship into vue js code

I have this project that should fetch values from a pivot table and one to many relationship. When using the eloquent syntax I am getting the correct output as seen here:
ReservationController
public function index()
{
$secSubs = Student::find(1);
return $secSubs->sectionSubjects;
}
form.blade.php
#inject('reservation', 'App\Http\Controllers\ReservationController')
#foreach( $reservation->index() as $reserved )
<tr>
<td>{{ $reserved->section->section_code }}</td>
<td>{{ $reserved->subject->subject_code }}</td>
<td>{{ $reserved->subject->subject_description }}</td>
<td>{{ $reserved->schedule }}</td>
<td>{{ $reserved->subject->units }}</td>
<td>{{ $reserved->room_no }}</td>
<td>
<button class="btn btn-xs btn-danger">Delete</button>
</td>
</tr>
#endforeach
However I want to make use of the feature of vue js so that my page will automatically be populated with value being fetch as seen below.
new Vue({
el: '#app-layout',
data: {
subjects: []
},
ready: function(){
this.fetchSubjects();
},
methods:{
fetchSubjects: function(){
var self = this;
this.$http({
url: 'http://localhost:8000/reservation',
method: 'GET'
}).then(function (subjects){
self.subjects = subjects.data;
console.log('success');
}, function (response){
console.log('failed');
});
},
}
});
form.blade.php
<tr v-for="subject in subjects">
<td>#{{ subject.section.section_code }}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>#{{ subject.room_no }}</td>
<td>
<button class="btn btn-xs btn-danger">Delete</button>
</td>
</tr>
As seen in my form.blade.php I cannot get the value of section_code. Am I missing something here?
UPDATE:
SectionSubject Model
class SectionSubject extends Model
{
protected $table = 'section_subject';
public function students()
{
return $this->belongsToMany(Student::class, 'section_subject_student','section_subject_id','student_id'
)->withTimestamps();
}
public function assignStudents(Student $student)
{
return $this->students()->save($student);
}
public function subject()
{
return $this->belongsTo(Subject::class);
}
public function section()
{
return $this->belongsTo(Section::class);
}
}
Student Model
public function sectionSubjects()
{
return $this->belongsToMany(SectionSubject::class,'section_subject_student', 'student_id','section_subject_id')
->withTimestamps();
}
Section Model
class Section extends Model
{
public function subjects()
{
return $this->belongsToMany(Subject::class)->withPivot('id','schedule','room_no');
}
public function sectionSubjects()
{
return $this->hasMany(SectionSubject::class);
}
}
it is not problem of laravel or vuejs.
this code.
this.$http({
url: 'http://localhost:8000/reservation',
method: 'GET'
}).then(function (subjects){
self.subjects = subjects.data;
console.log('success');
}, function (response){
console.log('failed');
});
you can see this ajax request will get answer in json.
and json is pretty much static content. as "Eloquent" within php scope its an object so if you ask relational data from it, it will execute call and return its relational data but json can not do that.
so to make it work you need to convert whole relational data and create one massive array which holds all relational data then encode it.
for example :
$user = App\User::with('roles')->first();
return $user->toJson();
now if you return this it will contain "user.roles.name" this value as we eagerly loaded that and converted to json.
in you case :
$subjects = App\Reservation::with('section')->all();
return $subjects->toJson();
now you can use subjects and loop it "subject.section.section_code" as section is eagerly loaded and added to array and converted to json.
I hope this will solve your problem.

Resources