Eloquent deleting model event doesn't fire - laravel-4

I have 2 models defined:
Program model:
class Program extends \Eloquent {
protected $guarded = [];
public static function boot()
{
parent::boot();
static::deleting(function($program)
{
DB::table('descriptions')->where('id',$program->id)->delete();
return true;
});
}
public function description()
{
return $this->hasOne('Description');
}
}
Description model, where description for the program is defined
class Description extends \Eloquent {
protected $guarded = [];
public function program()
{
return $this->belongsTo('Program','id','id');
}
}
When I delete Program with specific name I want the description for that program to be deleted too.
So:
Program::where('name',Input::get('name'))->delete();
Unfortunately this code doesn't fire "deleting" event for Program model and the description isn't deleted.
Whats wrong ?

The solution is :
Program::where('name',Input::get('name'))->first()->delete();

Related

How to display owner of a post in laravel admin list display?

public function index()
{
$query = Activity::orderBy('id','DESC')->with('provinces');
if(!Auth::user()->hasRole('Administer')){
$query=$query->where('province_id', Auth::user()->id);
}
$activities = $query->latest()->get();
return view('activity.index',compact('activities'));
}
How to display owner of a post in laravel admin list display?
My User Model
class User extends Authenticatable implements HasMedia
{
public function activities()
{
return $this->hasMany(Activity::class);
}
}
My Activity Model:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function provinces()
{
return $this->belongsToMany(Province::class);
}
}
My province Model
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->belongsToMany(Activity::class);
}
public function user()
{
return $this->belongsToMany(User::class);
}
}
I want to show the content to the user by province.
And also the admin can see all the content.
please help me i am new in laravel
Based on your comment, you should change your province conditions to:
if (!Auth::user()->hasRole('Administer')) {
$query = $query->where('province_id', Auth::user()->province_id);
}
You have defined that each activity belongs to an user. So can access owner of each activity like this:
$activity->user->name;
And if your activity belongs to a province, you should define your relation in this way:
class Activity extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function province()
{
return $this->belongsTo(Province::class);
}
}
Also for your Province model:
class Province extends Model
{
protected $fillable = [ 'title', 'post_id'];
public function activities()
{
return $this->hasMany(Activity::class);
}
public function users()
{
return $this->hasMany(User::class);
}
}
And this is best practice to use eager loading for fetching related records. It will look like this one:
$query = Activity::with(['user', 'province'])->orderBy('id','DESC');
Also another hint: try to use better variable names. You can use $activities instead of $query.

Call to undefined relationship on model

We have the following class using $with:
class CargaHorasEmpleado extends Model
{
protected $table = "empleados_horas";
protected $with = ["tipoTarea", "proyecto", "empleado", "empleadoQueHizoLaCarga"];
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id')->withTrashed();
}
public function empleado()
{
return $this->belongsTo('App\Empleado', 'id_empleado', 'id')->withTrashed();
}
public function empleadoQueHizoLaCarga()
{
return $this->belongsTo('App\Empleado', 'id_empleado_cargo_hs', 'id')->withTrashed();
}
public function proyecto()
{
return $this->belongsTo('App\Proyecto', 'id_proyecto', 'id')->withTrashed();
}
}
This is the class TipoTarea
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoTarea extends Model
{
protected $table = 'tipos_tareas';
public $timestamps = false;
protected $fillable = [
'titulo', 'descripcion'
];
}
Thep page throws the error: "Call to undefined relationship [tipoTarea] on model [App\CargaHorasEmpleado]". That's the only relationship that's not working. The others are fine. What's wrong?
Well, isn't the relationship called "tipoTarea"? You wrote "tiposTarea"
The problem was that my class "TipoTarea" didn't use softdeletes. So the error was in using the "WithTrashed" method. The correct way is:
public function tipoTarea()
{
return $this->belongsTo('App\TipoTarea', 'id_tipo_tarea', 'id');
}

Soft Deleting through relationships

I am trying to understand something.
I have a Project Model.
A Project can have many Document.
A Document has many DocumentData.
So this is straight forward, I have my models set up like so
class Project extends Model
{
protected $table = 'projects';
protected $guarded = [];
use SoftDeletes;
public function document()
{
return $this->hasMany('App\document', 'projectId');
}
public static function boot()
{
parent::boot();
static::deleted(function($document)
{
$document->delete();
});
}
}
class Document extends Model
{
use SoftDeletes;
protected $table = 'document';
protected $guarded = [];
public function project()
{
return $this->belongsTo('App\Project', 'projectId');
}
public function documentData()
{
return $this->hasMany('App\DocumentData', 'documentId');
}
public static function boot()
{
parent::boot();
static::deleted(function($document)
{
$document->documentData()->delete();
});
}
}
class DocumentData extends Model
{
use SoftDeletes;
protected $table = 'document_data';
protected $guarded = [];
public function document()
{
return $this->belongsTo('App\Document', 'documentId');
}
}
I am trying to understand the boot function and whether I have set it up properly? When I delete a project, its deleted_at timestamp is set. I am also looking for it to set the deleted at timestamp for all of that Projects Documents and DocumentData.
At the moment, when I delete a Project, on its deleted_at timestamp is set. The Document and DocumentData remains null.
How can I get it soft deleting through all related models?
Thanks
You're using the boot method correctly. The only thing i notice is a mistake in the handler of your Project's deleted event. You're trying to delete the instance again after it's been deleted. Instead, i suppose, you want to delete the associated Documents like so:
public static function boot()
{
parent::boot();
static::deleted(function($project)
{
$project->document()->delete();
});
}
Alternative Method:
The way i usually delete children is to override the delete() method on the parent models. I prefer the resulting code that way, but that's just a personal preference.
In your case that would be:
class Project extends Model {
public function delete()
{
parent::delete(); // first delete the Project instance itself
$this->document()->delete(); // delete children
}
}
class Document extends Model {
public function delete()
{
parent::delete();
$this->documentData()->delete();
}
}

Laravel 'boot' function is not firing

I have the following in an eloquent model
class Bucket extends \Eloquent {
protected $fillable = ['name'];
protected $appends = ['slug'];
public function __construct(){
$this->key = substr(str_shuffle(MD5(microtime())), 0, 24);
}
public static function boot(){
dd('check');
}
public function users(){
return $this->belongsToMany('User');
}
public function getSlugAttribute(){
return slugify($this->name);
}
}
However I'm able to read and update the model with no problem. I was under the impression boot was supposed to be called every time a model was instantiated, is that wrong?
Here's one of the controllers I use to view all the buckets
public function index()
{
return Auth::user()->buckets;
}
In your constructor, try calling
parent::__construct();

Model Event not working

I have the following model:
class ProjectTwitterStatus extends Eloquent {
protected $table = 'project_twitter_statuses';
protected $softDelete = true;
protected $guarded = array('id');
public static function boot()
{
parent::boot();
ProjectTwitterStatus::deleting(function($projectTwitterStatus)
{
$projectTwitterStatus->deleted_by = Auth::user()->id;
});
}
public function twitterStatus() {
return $this->belongsTo('TwitterStatus');
}
public function twitterRetweet() {
return $this->belongsTo('TwitterRetweet','twitter_status_id','twitter_status_id');
}
public function project() {
return $this->belongsTo('Project');
}
}
Somewhere in my app an item is deleted using one of the following statements:
ProjectTwitterStatus::find($id)->delete();
ProjectTwitterStatus::whereIn('twitter_status_id', $twitterStatusIds)->delete();
I can see in the database the item had been (soft) deleted. But the deleted_by column is not filled.
Does anyone know what I am doing wrong?
Try using Late Static Binding, like following-
class ProjectTwitterStatus extends Eloquent {
public static function boot ()
{
parent::boot();
static::deleting(function($projectTwitterStatus)
{
$projectTwitterStatus->deleted_by = Auth::user()->id;
});
}
}

Resources