Я использую Laravel
и vue
и работаю с fullCalendar
.
Я просто пытаюсь сохранить идентификатор пользователя, который создает событие в календаре, но я получаю null
значение ... Я не думаю, что у меня есть CalendarComponent. vue и CalendarResource. php установлены правильно?
Как мне сделать запрос на получение идентификатора пользователя?
Я использую этот код от github @ https://github.com/rcvioleta/fullcalendar-with-laravel-and-vue. У него также есть прогулка по YouTube https://www.youtube.com/watch?v=x_WMkIKztRQ&t=1545s
Я получаю эту ошибку:
Невозможно добавить новое событие! Объект {message: «Аргумент 1, переданный в Illuminate \ Database \ Grammar :: parameterize (), должен иметь тип массива, задан ноль, вызываться в / home / vagrant / www/calendar/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php в строке 869», исключение: «Symfony \ Component \ Debug \ Exception \ FatalThrowableError ", файл:" / home / vagrant / www/calendar/vendor/laravel/framework/src/Illuminate/Database/Grammar.php ", строка: 136, трассировка: (49) […]}
моей базы данных. таблица календаря
public function up()
{
Schema::create('calendars', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id')->unsigned()->index();
$table->string('event_name');
$table->text('event_description')->nullable();
$table->date('start_date');
$table->date('end_date');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Я установил отношения между таблицей пользователей и календаря:
Календарь. php Модель
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Calendar extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
Пользователь. php Модель
public function calendars()
{
return $this->hasMany(Calendar::class);
}
Мой CalendarResource. php .. Я добавил 'user_id => $ this-> user_id, я не знаю, правильно ли это?
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CalendarResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'user_id' => $this->user_id,
'description' => $this->event_description,
'title' => $this->event_name,
'start' => $this->start_date,
'end' => $this->end_date
];
}
}
Мой CalendarComponent. vue ... Я добавил User_id [] в data () return..Я добавил идентификатор пользователя в шоу даже ...
showEvent(arg) {
this.addingMode = false;
const { id, user_id, title, description, start, end } = this.events.find(
event => event.id === +arg.event.id
);
Мой CalendarComponent. vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form @submit.prevent>
<div class="form-group">
<label for="event_name">Event Name</label>
<input type="text" id="event_name" class="form-control" v-model="newEvent.event_name">
</div>
<div class="form-group">
<label for="message">Event Description</label>
<textarea id="event_description" cols="30" rows="4" class="form-control" v-model="newEvent.event_description"></textarea>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="start_date">Start Date</label>
<input
type="date"
id="start_date"
class="form-control"
v-model="newEvent.start_date"
>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="end_date">End Date</label>
<input type="date" id="end_date" class="form-control" v-model="newEvent.end_date">
</div>
</div>
<div class="col-md-6 mb-4" v-if="addingMode">
<button class="btn btn-sm btn-primary" @click="addNewEvent">Save Event</button>
</div>
<template v-else>
<div class="col-md-6 mb-4">
<button class="btn btn-sm btn-success" @click="updateEvent">Update</button>
<button class="btn btn-sm btn-danger" @click="deleteEvent">Delete</button>
<button class="btn btn-sm btn-secondary" @click="addingMode = !addingMode">Cancel</button>
</div>
</template>
</div>
</form>
</div>
<div class="col-md-8">
<Fullcalendar
@eventClick="showEvent"
:plugins="calendarPlugins"
:events="events"
:header="{
left: 'title',
center: 'dayGridMonth, timeGridweek, timeGridDay, listWeek',
right: 'prev today next'
}"
:eventLimit="6"
/>
</div>
</div>
</div>
</template>
<script>
import Fullcalendar from "@fullcalendar/vue";
import TimeGridPlugin from "@fullcalendar/timegrid";
import ListPlugin from "@fullcalendar/list";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import axios from "axios";
export default {
components: {
Fullcalendar
},
data() {
return {
calendarPlugins: [dayGridPlugin, interactionPlugin, TimeGridPlugin, ListPlugin],
events: "",
newEvent: {
user_id: [],
event_description: "",
event_name: "",
start_date: "",
end_date: ""
},
addingMode: true,
indexToUpdate: ""
};
},
created() {
this.getEvents();
},
methods: {
addNewEvent() {
axios
.post("/api/calendar", {
...this.newEvent
})
.then(data => {
this.getEvents(); // update our list of events
this.resetForm(); // clear newEvent properties (e.g. title, start_date and end_date)
})
console.log(response.data)
.catch(err =>
console.log("Unable to add new event!", err.response.data)
);
},
showEvent(arg) {
this.addingMode = false;
const { id, user_id, title, description, start, end } = this.events.find(
event => event.id === +arg.event.id
);
this.indexToUpdate = id;
this.newEvent = {
event_name: title,
event_description: description,
start_date: start,
end_date: end
};
},
updateEvent() {
axios
.put("/api/calendar/" + this.indexToUpdate, {
...this.newEvent
})
.then(resp => {
this.resetForm();
this.getEvents();
this.addingMode = !this.addingMode;
})
.catch(err =>
console.log("Unable to update event!", err.response.data)
);
},
deleteEvent() {
axios
.delete("/api/calendar/" + this.indexToUpdate)
.then(resp => {
this.resetForm();
this.getEvents();
this.addingMode = !this.addingMode;
})
.catch(err =>
console.log("Unable to delete event!", err.response.data)
);
},
getEvents() {
axios
.get("/api/calendar")
.then(resp => (this.events = resp.data.data))
.catch(err => console.log(err.response.data));
},
resetForm() {
Object.keys(this.newEvent).forEach(key => {
return (this.newEvent[key] = "");
});
}
},
watch: {
indexToUpdate() {
return this.indexToUpdate;
}
}
};
</script>
<style lang="css">
@import "~@fullcalendar/core/main.css";
@import "~@fullcalendar/daygrid/main.css";
@import "~@fullcalendar/timegrid/main.css";
.fc-title {
color: #fff;
}
.fc-title:hover {
cursor: pointer;
}
</style>