简体   繁体   中英

How to pass a variable from controller to eloquent in Laravel

I created a new attribute (duration) in my model, the main purpose of creating this attribute is to calculate slots according to a specific time duration. though I can set this attribute with the instance of the model that i am creating in controller but when I am fetching multiple rows it is not working, I would be very thankful for your suggestions about getting a solution for this problem.

Here is my code.

Controller

public function index(Request $request)
{
    $counselor = $this->myCounselor($request);
    $counselor_id = $counselor !== null? $counselor->counselorid: null; 
    $date = $request->input('date');

    $availabilities = Availability::where('status', '=', 1)
        ->when($counselor_id, function ($query, $counselor_id) {
            return $query->where('counselor_id', $counselor_id);
        })
        ->when($date, function ($query, $date) {
            return $query->whereDate('date', $date);
        })
        ->where(function($query) {
            return $query->where('date' , '!=', null)
                         ->whereDate('date', '>=', date('Y-m-d'));
        })
        ->orderBy('date', 'desc')
        ->get();

        // $availabilities->duration = 20;

        return response()->json($availabilities);

        // return view('schedule');
    }

Model

class Availability extends Model
{
    use HasFactory, CalculateSlots;

    protected $attributes = ['available_slots', 'duration' => 20];
    protected $appends = ['available_slots'];

    public function getAvailableSlotsAttribute()
    {
        return $this->getSlots($this->duration); // I am trying to set this duration attribute's value in my controller.
    }
}

try like this:

public function index(Request $request)
{
    $a = new Availability ();
    return $a->getAvailableSlotsAttribute();
}

Or use scope before your method name in your model , like:

public function scopegetAvailableSlotsAttribute(){

}

In controller you can get it like:

Availability::getAvailableSlotsAttribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM