您将如何用雄辩-Laravel 5.2做到这一点



我在控制器中具有此逻辑:

// hydratation part 1 (cf son modele) 
    $matiere->fill($request->all());
    
// hydratation part 2 with attributes not in the POST
    $matiere->id_ecole = Session::get('id_ecole');
    $request->has('matiere_inactive') ? $matiere->matiere_inactive = '1' : $matiere->matiere_inactive = null;
    if ($matiere->exists) {
        $matiere->auteur_modif = Session::get('nom').' '.Session::get('prenom');
    } else {
        $matiere->auteur_creation = Session::get('nom').' '.Session::get('prenom');
    }

我认为第2部分可能存在于模型中,而不是控制器(我喜欢具有"简短"控制器)。

是个好主意吗?

如果是,我该怎么做?

我的模型是:

class Matiere extends Model {
    protected $table = 'matiere';
    protected $primaryKey = 'id_matiere';
    
    protected $fillable = [
        'id_matiere',
        'code_court_matiere',
        'libelle_matiere'
    ];
    
    public function setCodeCourtMatiereAttribute($value)
    {
        $this->attributes['code_court_matiere'] = strtoupper($value);
    }
    public function setLibelleMatiereAttribute($value)
    {
        $this->attributes['libelle_matiere'] = ucwords($value);
    }
    
}

laravel 5. 3

您可以通过在Matiere模型上创建方法来做到这一点。

Here is a simple example: 
ExampleController.php
$mat = new AppMatiere();
$feedback = $mat->addm($request);

Matiere.php
public function addm($request)
{
    $this->id_ecole = Session::get('id_ecole');
    $request->has('matiere_inactive') ? $this->matiere_inactive = '1' : $this->matiere_inactive = null;
    $this->save();
    return $this->id;
}

相关内容

最新更新