Я работаю над своим API сегодня, и у меня много проблем с получением моих модельных событий, у меня есть 2 события в настоящее время, событие создания события и обновления, логика следующая:Laravel Model Events
class Project extends Eloquent {
protected $fillable = [
'name',
'description',
'total_cost',
'start_date',
'finish_date',
'sales_person',
'project_manager',
'client_id',
'organisation_id',
'user_id'
];
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
public static function boot()
{
parent::boot();
static::created(function($project)
{
// Save the notifications for the user various users on the project
// The projects organiastion owners need to be told that a project has been created.
$notifyUsers = array();
foreach($project->organisations->users as $person) {
if($person->pivot->is_admin == "1" && $person->pivot->user_id != $project->user_id) {
$notifyUsers[]['id'] = $person->pivot->user_id;
}
}
$notification = new Notification;
//return $notification;
//die(print_r($project));
$notification->withBody($project->user->first_name . " " . $project->user->last_name . " created the project " . $project->name);
$notification->withURI($project->slug);
$notification->withIsNotification(1);
$notification->regarding($project);
$notification->withType('created');
$notification->deliver($notifyUsers);
});
static::updated(function($project)
{
exit('!!!');
foreach($project->organisations->users as $person) {
if($person->pivot->is_admin == "1" && $person->pivot->user_id != $project->user_id) {
$notifyUsers[]['id'] = $person->pivot->user_id;
}
}
return true;
});
}
}
Созданный метод работает отлично, но метод обновления никогда не работает, выход никогда не попадает. Я обновляю свою модель с помощью запроса PUT, который попадает этот метод в мой контроллер,
public function edit($id)
{
//if project have been seen
if(Input::get('viewed')){
$project = Project::find($id);
//update to show that user have viewd this project
$project->projectview()->attach($id,array('user_id'=>ResourceServer::getOwnerId()));
$project->load('projectview');
return Response::json($project, 200);
}
$rules = array(
// 'name' => 'required',
'total_cost' => 'numeric',
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails()) {
return Response::json($validation->messages()->first(), 500);
} else {
$project = Project::find($id);
$vars = array();
foreach(Input::all() as $key => $value) {
$vars[$key] = $value;
}
$projectToUpdate = $project->toArray();
unset($projectToUpdate['created_at']);
unset($projectToUpdate['updated_at']);
if(Input::get('project_name') || Input::get('name')){
$project->name = Input::get('project_name')?Input::get('project_name'):Input::get('name');
$project->uri_hash = Stringhelpers::_slugify($project->name);// $this->_slugify($project->name);
}
$project->slug = $project->slug;
// $project->slug = Stringhelpers::_uriHash(time().$project->name);
$project->description = Input::get('description') ? Input::get('description'):$project->description;
$project->total_cost = Input::get('total_cost') ? Input::get('total_cost') : $project->total_cost;
$project->start_date = Input::get('start_date') ? Input::get('start_date') : $project->start_date;
$project->finish_date = Input::get('finish_date') ? Input::get('finish_date'): $project->finish_date ;
//if start date is passed finish date
$start_date_moment = new \Moment\Moment($project->start_date);
$finish_date_moment = new \Moment\Moment($project->finish_date);
if($start_date_moment->isAfter($finish_date_moment)){
$project->start_date = $start_date_moment->cloning()->startOf('week')->format('Y-m-d H:i:s');
$project->finish_date = $start_date_moment->cloning()->endOf('week')->format('Y-m-d H:i:s');
}
$project->status = Input::get('status') ? Input::get('status') : $project->status;
// $project->user_id = ResourceServer::getOwnerId();
$project->invoiced_at = Input::get('invoiced_at') ?Input::get('invoiced_at'):null;
$project->archived_at = Input::get('archived_at') ? Input::get('archived_at') : "0000-00-00 00:00:00";
$project->is_internal = Input::get('is_internal') ?Input::get('is_internal'):0;
//return Input::get('name');
$locked_by = "";
if(Input::get('locked_by') == "0") {
$locked_by = NULL;
}
if(is_null($locked_by)) {
$project->locked_by = $locked_by;
} elseif(Input::get('locked_by') != '0') {
$project->locked_by = Input::get('locked_by');
} else {
$project->locked_by = $project->locked_by;
}
if(Input::get('owner') != 'user') {
$project->organisation_id = Input::get('organisation_id') ? Input::get('organisation_id') : $project->organisation_id;
$project->owner_id = Input::get('organisation_id') ? Input::get('organisation_id'): $project->owner_id ;
$project->client_id = Input::get('client_id') ? Input::get('client_id') : $project->client_id;
} else {
// $project->user_id = Input::get('user_id') ? Input::get('user_id') : $project->user_id ;
$project->owner_id = Input::get('owner_id') ? Input::get('owner_id') : $project->owner_id ;
$project->organisation_id = Input::get('organisation_id') ? Input::get('organisation_id') : $project->organisation_id;
$project->client_id = Input::get('client_id') ? Input::get('client_id') : $project->client_id;
}
if(is_array(Input::get('sales_person'))) {
$project->sales_person = Input::get('sales_person.id') ? Input::get('sales_person.id') : $project->sales_person ;
} else {
$project->sales_person = Input::get('sales_person') ? Input::get('sales_person') : $project->sales_person ;
}
$project->client_id = Input::get('client_id') ? Input::get('client_id') : $project->client_id;
$client_user_detail = DB::table('users')
->leftjoin('client_user','users.id','=','client_user.user_id')
->where('client_user.client_id', '=', Input::get('client_id'))
->orWhere('users.id', '=', $project->owner_id)
->get();
if($project->organisation_id == ''){
$client_user_detail = DB::table('users')
->select('users.id','users.email','users.first_name','users.last_name','users.display_name','users.initials','users.invite_code','projects.owner_id')
->leftjoin('projects','users.id','=','projects.owner_id')
->leftjoin('client_user','users.id','=','client_user.user_id')
->where('client_user.client_id', '=', Input::get('client_id'))
->orWhere('users.id', '=', $project->owner_id)
->distinct()
->get();
}else{
$client_user_detail = DB::table('users')
->leftjoin('client_user','users.id','=','client_user.user_id','users.invite_code')
->leftjoin('client_organisation','client_user.user_id','=','client_organisation.client_id')
->leftjoin('organisations','client_organisation.organisation_id','=','organisations.id')
->where('client_user.client_id', '=', Input::get('client_id'))
->get();
}
$collab_id = array();
$team_id = array();
$pm_id = array();
//return Input::get('collaborators');
if(is_array(Input::get('collaborators'))){
//return Input::get('collaborators');
$collabo = Input::get('collaborators');
if(empty($collabo)){
$project->collaborators()->detach();
}else{
foreach($collabo as $collab) {
$collab_id[] = $collab['id'];
}
}
}
if(is_array(Input::get('project_manager'))){
$managers = Input::get('project_manager');
if(empty($managers)){
$project->projectmanager()->detach();
}else{
foreach($managers as $pm) {
$pm_id[] = $pm['id'];
}
}
}
if($project->save()) {
if(isset($collab_id) && Input::get('collaborators')) {
$project->collaborators()->sync($collab_id);
}
if(isset($pm_id) && Input::get('project_manager')) {
$project->projectmanager()->sync($pm_id);
}
// $project->organisations()->sync(array($project->organisation_id));
$project->load('clients');
$project->load('projectmanager');
$project->load('salesperson');
$project->load('collaborators');
$project->load('user');
$project->load('projectview');
$project->client_user = $client_user_detail;
//return json_encode(array("id" => Input::get('socketId')));
Pusherer::trigger('project_'.$project->id, 'post:change', json_encode(Input::all()), Input::get('socketId'));
return Response::json(array('text' => 'Successful!'), 200);
} else {
return Response::json(array('error', 'Somthing has gone wrong!'), 500);
}
}
база данных на самом деле обновляется, но событие модель просто не бывает, я не знаю, почему это ?
Событие запускается для меня. Вы уверены, что сохранение() происходит, и данные обновляются в базе данных? Получаете ли вы «Successufl!»? ответ? –
Да, я получаю ответ 200, и строка базы данных обновляется. – Udders