Search code examples
phplaravellaravel-5

Automatic status on 2 models


I am stuck since 2 days on a problem that I haven't think before.

To be simple, I manage 3 models (Motorbike, Revision, Training).

If a motorbike is in revision or in training, I have to see on my form Motorbike that the moto is unavailable.

Example:

There are a training on 10/08/2019 with the motorbike 00004.

enter image description here

In my form Motorbike, the status has changed in unavailable for the motorbike 000004.

enter image description here

Well !

Now, my problem is in my form Revision, if I add a revision for the motorbike 000002

enter image description here

the status has to change in my form Motorbike also. Here the status has not changed...

enter image description here

In my Controller Motorbike I have this:

public function index()
    {
        $motorbikes = Motorbike::oldest()->paginate(5);

        $bikeIdsDown = Revision::where('date_revision_start', "<=" , Carbon::now())->where('date_revision_end', ">=", Carbon::now())->pluck('fk_motorbike')->toArray();

        $bikeIdsDown = Training::where('date_sitting', "<=" , Carbon::now())->pluck('fk_motorbike')->toArray();

        return view('admin.motorbikes.index', compact('motorbikes', 'bikeIdsDown'))
          ->with('i', (request()->input('page',1) -1)*5);
    }

But, I think my problem is in my index.blade

@foreach($motorbikes as $motorbike)
    <tr>
    <td>{{$motorbike->matriculation }} </td>
    <td>{{$motorbike->number_motorbike}}</td>
    <td> @if(in_array($motorbike->id, $bikeIdsDown))
         UNAVAILABLE
         @else
         Available
         @endif
    </td>

My array is used only for a model?


Solution

  • this is happing with you because you are overriding the same variable.

    
     $bikeIdsDown = Revision::where('date_revision_start', "<=" , Carbon::now())->where('date_revision_end', ">=", Carbon::now())->pluck('fk_motorbike')->toArray();
    
     $bikeIdsDown = Training::where('date_sitting', "<=" , Carbon::now())->pluck('fk_motorbike')->toArray();
    
    

    you are using a $bikeIdsDown variable for both query response.

    change the $bikeIdsDown variable to an array to assign a new value.

     $bikeIdsDown = Revision::where('date_revision_start', "<=" , Carbon::now())->where('date_revision_end', ">=", Carbon::now())->pluck('fk_motorbike')->toArray();
    
     $bikeIdsDown[] = Training::where('date_sitting', "<=" , Carbon::now())->pluck('fk_motorbike')->toArray();
    

    or create a new array and merge like :

     $revisionId = Revision::where('date_revision_start', "<=" , Carbon::now())->where('date_revision_end', ">=", Carbon::now())->pluck('fk_motorbike')->toArray();
    
     $trainingId = Training::where('date_sitting', "<=" , Carbon::now())->pluck('fk_motorbike')->toArray();
    
    $bikeIdsDown = array_merge($revisionId, $trainingId);