Обновите столбец, нажав кнопку одобрить и отклонить - PullRequest
1 голос
/ 16 марта 2020

Вот мой dashboard.blade. php

<td>
 <a href="#" class="btn btn-success">Approve</a>
</td>
<td>
 <a href="#" class="btn btn-danger">Decline</a>
</td>

Вот мой LeaveController. php


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Redirect;   // using redirect 
use Auth;       // import auth
use App\Models\LeaveType;
use App\Models\StatusType;
use App\Models\Leave;

class LeaveController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $leaves = Leave::with('type', 'applied_by','statustype')->where('user_id', Auth::id())->get();
        return view('leave.index', compact('leaves'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $leavetypes = LeaveType::all(); // multiple select view (LeaveType is the model)
        return view('leave.create', compact('leavetypes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $leave = $request->get('leave');
        $leave['user_id'] = Auth::id();
        $leave['status_id']= StatusType::find(1)->id;
        $leave = Leave::create($leave);

        return Redirect::to(route('leave.create'));


    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $leave = Leave::with('type', 'applied_by', 'statustype')->find($id);
        return view ('leave.show', compact('leave'));


    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

index.blade. php

@extends('layouts.master')

@section('title')

User Dashboard

@endsection

@section('content')

<div class="row">
  <div class="col-md-12">
    <div class="card">
      <div class="card-header"> 
        <h4 class="card-title">Leave Status</h4>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <thead class=" text-primary">
            <th>ID</th>
            <th>Leave Type</th>
            <th>Leave Start date</th>
            <th>Leave End date</th>
            <th>Status<th>
            <th>Action</th>
            </thead>
            <tbody> 
              @foreach ($leaves as $leave)          
              <tr>
                <td>{{$leave->id}}</td>
                <td>{{$leave->type->type}}</td>
                <td>{{$leave->start}}</td>
                <td>{{$leave->end}}</td>
                <td>{{$leave->statustype->status}}</td> 
                <td>
                </td>
                <td>
                    <a href="{{ route('leave.show', $leave->id) }}" class="btn btn-warning">View</a>
                </td>
              </tr> 
              @endforeach

            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-12">
    <div class="card card-plain">
      <div class="card-header">
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">


          </table>
        </div>
      </div>
    </div>
  </div>
</div>


@endsection

@section('scripts')
@endsection

Выйти из модели

<?php

 namespace App\Models;

 use Illuminate\Database\Eloquent\Model;

 class Leave extends Model
 {
  protected $fillable = [
    'type_id', 'start', 'end', 'remarks', 'user_id','status_id'
  ];

  public function applied_by()
  {
    return $this->belongsTo('App\User', 'user_id');
  }

  public function type()
  {
    return $this->belongsTo('App\Models\LeaveType', 'type_id');
  }

  public function statustype()
  {
    return $this->belongsTo('App\Models\StatusType','status_id');
  }
 }

Модель статического типа

 <?php

  namespace App\Models;

  use Illuminate\Database\Eloquent\Model;

  class Leave extends Model
  {
    protected $fillable = [
    'type_id', 'start', 'end', 'remarks', 'user_id','status_id'
    ];

   public function applied_by()
   {
    return $this->belongsTo('App\User', 'user_id');
    }

   public function type()
   {
    return $this->belongsTo('App\Models\LeaveType', 'type_id');
    }

   public function statustype()
   {
    return $this->belongsTo('App\Models\StatusType','status_id');
   }
  }

Сеялка StatusType

   <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

     class Leave extends Model
     {
       protected $fillable = [
     'type_id', 'start', 'end', 'remarks', 'user_id','status_id'
      ];

     public function applied_by()
     {
      return $this->belongsTo('App\User', 'user_id');
      }

     public function type()
     {
     return $this->belongsTo('App\Models\LeaveType', 'type_id');
     }

     public function statustype()
    {
     return $this->belongsTo('App\Models\StatusType','status_id');
    }
   }

Как обновить столбец состояния, нажимая кнопки

Мне еще нужно указать какой-либо маршрут. Я не совсем понимаю, где поставить условие: в функции обновления или отдельно.

1 Ответ

0 голосов
/ 16 марта 2020

Маршруты ресурсов называются по-разному проверьте ниже

Route::group(['middleware' => ['auth']], function () {

Route::resource('leave', 'LeaveController', ['names' => [

    'index' => 'leave.index',
    'create' => 'leave.create',
    'store' => 'leave.store',
    'show' => 'leave.show',
    'edit' => 'leave.edit',
    'update' => 'leave.update',
    'destroy' => 'leave.destroy',
]]);

});

В вашем dashboard.blade. php вы можете определить маршрут с помощью Передав соответствующий идентификатор на кнопку. Я изменил тег href на кнопку. Он может использовать тот же класс, что и класс href, который вы использовали ранее. При нажатии этой кнопки она вызовет функцию обновления с методом put.

Каждый идентификатор будет иметь кнопки активации и деактивации и отличается своим атрибутом имени как act и deact .

Примечание : При определении маршрутов PUT, PATCH или DELETE, которые вызываются из формы HTML, вам необходимо добавить в форму скрытое поле _method. Значение, отправленное с полем _method, будет использоваться в качестве метода HTTP-запроса .

{{Form::open(array('url'=>'leave/update','method'=>'post','class'=>'form-login'))}}
 <input type="hidden" name="_method" value="PUT">
 <input type="hidden" name="_token" value="{{ csrf_token() }}">
 <button  class ="btn btn-success" name="act" value="{{$leave->id}}">activate</button>
 <button  class ="btn btn-success" name="deact" value="{{$leave->id}}">deactivate</button>
{{Form::close()}}

Определите соответствующие функции в вашем LeaveController и обновите соответствующим образом. Если нажата кнопка активации / деактивации, затем нажмите соответственно обновите поле статуса этого идентификатора:

  public function update(Request $request, $id)
{
    if(isset($request->act)) { //if you click activate button, update accordingly
      $leaveId = $request->act; 
      \App\Models\Leave::where('id', $leaveId )->update(['status' => 1]);
    }if(isset($request->deact)) { //if you click deactivate button, update accordingly
      $leaveId = $request->deact;
      \App\Models\Leave::where('id', $leaveId )->update(['status' => 2]);
    }

}
...