0

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 don't know how to send the value(3 or other else) via $category query.

1
  • I think you have to add limit(3) to the relation. Also it could be useful if you post the relations, for clarity. Commented Sep 30, 2021 at 0:33

2 Answers 2

1

You can simply put conditions in the closure of the "film" relationship on the controller to get 3 action movies or any number of movies.

Controller:

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

}])->where('name','=','Action')->first();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your solution also works :)
0

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);
   } 

2 Comments

@Richard how does this answer achieve your goal of limiting the query to a certain number of results? I see no code here that would do any sort of limiting.
@miken32 if you can follow the issue tell the end, you would see how this solves his problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.