I have a Lesson
Model like this :
class Lesson extends Model
{
use SoftDeletes;
public $primaryKey = 'lesson_id';
public function contents ()
{
return $this->hasMany('App\Content', 'lesson_id', 'lesson_id');
}
}
And a `Content Model like this :
class Content extends Model
{
public $primaryKey = 'content_id';
public $timestamps = false;
public $fillable = ['lesson_id', 'order'];
public function lesson ()
{
return $this->belongsTo('App\Lesson', 'lesson_id', 'lesson_id');
}
}
In Content
Model, there is an order column that increases after each content insertion based on lesson_id
field like this:
|------|---------|---------------|
| id |lesson_id | order |
|------|---------|---------------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 1 | 4 |
| 6 | 1 | 5 |
| 7 | 2 | 2 |
| 8 | 3 | 1 |
| 9 | 3 | 2 |
|------|---------|---------------|
For that I must run below codes before each insertion query to Calculate order
column for a specific lesson_id
:
$lesson_id = $request->get('lesson_id')
$lastOrder =
Content::whereHas('lesson', function ($query) use ($lesson_id) {
$query->where('lesson_id', $lesson_id);
})->max('order');
if (is_null($lastOrder)) {
$lastOrder = 0;
}
$newContent =
Content::create(
[
'lesson_id' => $lesson_id,
'order' => $lastOrder + 1
]
);
I want a way in laravel that this operations done on insertion new Content instance automatically.
Does anyone have a solution to this problem?