Как вставить значение, которое не повторяется в Laravel - PullRequest
0 голосов
/ 24 января 2019

Как я могу вставить значение, которое не повторяется? Я работаю над системой учета времени, сейчас проблема в том, что я добавляю время и снова добавляю время, которое совпадает с днем ​​повторения времени. Как я могу вставить время, которое не повторяется, даже если я добавлю время снова? Большое спасибо, вот мой код. Возможно ли это сделать?

Мои текущие данные таковы, и мой окончательный вывод должен быть таким: employee_no 10310 должен быть только один и не повторять данные. Не следует повторять и не вставлять id 3.

enter image description here

Контроллер

public function insertSchedule(Request $request)
{
    $employeeTimeSet = new Schedule;
    $employeeTimeSet->employee_no = $request->input('hidEmployeeno');
    $employeeTimeSet->last_name = $request->input('hidEmployeeLast');
    $employeeTimeSet->first_name = $request->input('hidEmployeeFirst');
    $employeeTimeSet->date_today = $request->input('dateToday');
    $employeeTimeSet->time_in = $request->input('timeIn');
    $employeeTimeSet->time_out = $request->input('timeOut');
    $employeeTimeSet->save();

    $notification = array(
        'message' => 'Employee Time Set!',
        'alert-type' => 'success'
    );

    return redirect('/admin/employeemaintenance/createSchedule')->with($notification, 'Employee Time Set');
}

Посмотреть

{!! Form::open(['action' => 'Admin\EmployeeFilemController@insertSchedule', 'method' => 'POST']) !!}
<div class="row">
    <div class="form-group col-md-12">
        <small>Employee No. and Name:</small>
        <b><i> {{ $employee->employee_no }} : {{ $employee->last_name }}, {{ $employee->first_name }}</i></b>
        <input type="hidden" name="hidEmployeeno" value='<?php echo $employee->employee_no ?>'>
        <input type="hidden" name="hidEmployeeLast" value='<?php echo $employee->last_name ?>'>
        <input type="hidden" name="hidEmployeeFirst" value='<?php echo $employee->first_name ?>'>
        <hr>
    </div>
</div>
<table class="table">
    <thead>
    <tr>
        <th>DATE TODAY</th>
        <th>TIME IN</th>
        <th>TIME OUT</th>
        <th>ACTION</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td><b><?php  echo date("F-d-Y");  ?></b></td>
        <!---Date Hidden-->
        <input type="hidden" name="dateToday" value='<?php echo date("F-d-Y") ?>'>
        <td><input type="time" name="timeIn" class="form-control col-md-10"></td>
        <td><input type="time" name="timeOut" class="form-control col-md-10"></td>
        <td> {{Form::button('<i class="fa fa-clock">&nbsp;&nbsp;SET TIME</i>',['type' => 'submit','class' => 'btn btn-warning btn-sm',  'style'=>"display: inline-block;"])}}</td>
    </tr>
    </tbody>
</table>
{!! Form::close() !!}

Таблица базы данных

public function up()
{
    Schema::create('schedules', function (Blueprint $table) {
        $table->increments('id');
        $table->string('employee_no')->nullable();
        $table->string('last_name')->nullable();
        $table->string('first_name')->nullable();
        $table->string('date_today')->nullable();
        $table->string('time_in')->nullable();
        $table->string('time_out')->nullable();
        $table->timestamps();
    });
}

Ответы [ 3 ]

0 голосов
/ 24 января 2019

Я почти уверен, что вы могли бы улучшить это в другом аспекте вашего сайта, но, учитывая, что мы не знаем ваш вариант использования ... это должно сработать:

public function insertSchedule(Request $request)
{
    $schedule = Schedule::where('employee_no', $request->input('hidEmployeeno'))
                ->where('date_today', $request->input('dateToday'))
                ->where('time_in', $request->input('timeIn'))
                ->where('time_out', $request->input('timeOut'))
                ->first();

    if( ! $schedule)
    {
        $employeeTimeSet = new Schedule;
        $employeeTimeSet->employee_no = $request->input('hidEmployeeno'); 
        $employeeTimeSet->last_name = $request->input('hidEmployeeLast'); 
        $employeeTimeSet->first_name = $request->input('hidEmployeeFirst'); 
        $employeeTimeSet->date_today = $request->input('dateToday'); 
        $employeeTimeSet->time_in = $request->input('timeIn'); 
        $employeeTimeSet->time_out = $request->input('timeOut'); 
        $employeeTimeSet->save();

        $notification = array(
            'message' => 'Employee Time Set!',
            'alert-type' => 'success'
        );
    }
    else
    {
        $notification = array(
            'message' => 'The entry already exists!',
            'alert-type' => 'warning'
        );
    }


return redirect('/admin/employeemaintenance/createSchedule')
           ->with($notification, 'Employee Time Set');

}

0 голосов
/ 24 января 2019

Вы можете использовать firstOrNew ()

$employeeTimeSet = Schedule::firstOrNew(['employee_no' => $request->input('hidEmployeeno'), 'date_today' => $request->input('dateToday')]);
$employeeTimeSet->last_name = $request->input('hidEmployeeLast');
$employeeTimeSet->first_name = $request->input('hidEmployeeFirst');
$employeeTimeSet->time_in = $request->input('timeIn');
$employeeTimeSet->time_out = $request->input('timeOut');
$employeeTimeSet->save();
0 голосов
/ 24 января 2019

В вашей миграции обновите это

$table->string('employee_no')->nullable();

до этого:

$table->string('employee_no')->unique();
...