Home > other >  Laravel: How to send value from Controller to Model?
Laravel: How to send value from Controller to Model?

Time:09-30

How can i send a value from Controller to Model and how to receive the value in the Model.

I let above a picture of my database tables.

enter image description here

Example:If i enter in the input 3 action movies

 $category=category::with('film')->where('name','=','Action')->first();

Film model:3

class film extends Model{
    protected $table = "film";  //Para nao dar o erro de singular e plural
    protected $primaryKey = 'film_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['film_id', 'title', 'release_year'];

    public function category(){
        return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
   }   
}

Category model:

class category extends Model{
    protected $table = "category";
    protected $primaryKey = 'category_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['category_id','name'];

    public function film(){
        return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
    }
}

NOTE:I realized that i need to add in the front of the Category model

->take(3)

But i dont know how to send the value(3 or other else) via $category query. Thanks

CodePudding user response:

Controller Side

$category=category::with('film')->where('name','=','Action')->film->category($value);

Model Side

    public function category($value){
        return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
   } 

CodePudding user response:

you can simply put condition in the closure of "film" relationship on the controller to get 3 action movies or any no of movies

Controller:-

$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
    $query->limit($limt);

}])->where('name','=','Action')->first();
  • Related