Laravel: отправка нескольких входов из пошаговой формы в базу данных MYSQL в laravel - PullRequest
0 голосов
/ 04 ноября 2019

Я работаю над приложением Duty Log, в котором менеджер может вводить журналы (как правило, выдает) для каждого отдела в организации. У меня есть пошаговая форма с девятью наборами полей для 9 отделов (с идентификаторами, соответственно пронумерованными в том же порядке в базе данных. Каждый из девяти шагов имеет три входа (заголовок, комментарий и интервал) и кнопку «Далее», кроме последнего, в котором есть отправка. кнопка.

ожидаемый результат для формы для вставки в таблицу журналов, заголовок журнала, комментарий, интервал, идентификатор_пользователя, идентификатор_подраздела (это должно совпадать с отделом, в котором принадлежит текущий шаг)

вот мой контроллер журнала:

<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller; 
use App\Log;
use Auth;
use App\User;
use Illuminate\Http\Request; 

class LogController extends Controller 
{ 

      public function __construct()
    {
        $this->middleware('auth');


    }

    //Display a listing of the resource. 
    public function index()
{
     $logs = Log::all();

     return view('logs.index', compact('logs'));
}

    //Show the form for creating a new resource.
    public function create()
{
    return view('logs.create');
}

public function store(Request $request)
{   

    $validatedData = $request->validate([
         'comment' => 'required|max:255',
         'title' => 'required|max:50',
         'department' => $request->department()->id, 
         'user_id' => $request->user()->id, 
         'time' => 'required|max:50',
     ]);
     $log = Log::create($validatedData);


     return redirect('/logs')->with('success', 'log is successfully saved');
}

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($query) {
            $query->user_id = user()->id();
        });
    }
    // Create the resoource
    //Display the specified resource.
    public function show(Log $log)
    {
        // In an admin panel, I usually don't need this method. It's often more efficient to
        // show the log data in the edit view.
    }

    //Show the form for editing the specified resource.
    public function edit($id)
{
    $log = Log::findOrFail($id);

    return view('logs.edit', compact('log'));
}

    //Update the specified resource in storage.
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'comment' => 'required|max:255',
            'title' => 'required|max:50',
            'department' => $request->department()->id, 
            'user_id' => $request->user()->id, 
            'time' => 'required|max:50',
        ]);
        Log::whereId($id)->update($validatedData);

        return redirect('/logs')->with('success', 'Log is successfully updated');
    }

    //Remove the specified resource from storage.
    public function destroy($id)
    {
        $log = Log::findOrFail($id);
        $log->delete();

        return redirect('/log')->with('success', 'Log is successfully deleted');
    }
}

здесь 'контроллер отдела

<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller; 
use App\Department;
use Auth;
use App\User;
use Illuminate\Http\Request; 

class DepartmentController extends Controller 
{ 

      public function __construct()
    {
        $this->middleware('auth');


    }

    //Display a listing of the resource. 
    public function index()
{
     $departments = Department::all();

     return view('departments.index', compact('departments'));

}

    //Show the form for creating a new resource.
    public function create()
{   
    $departments = Department::all();
    return view('departments.create');
}

public function store(Request $request)
{   

    $validatedData = $request->validate([
         'name' => 'required|max:255',
         'head' => 'required|max:50',
     ]);
     $department = Department::create($validatedData);

     return redirect('/departments')->with('success', 'department is successfully saved');
}

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($query) {
            $query->user_id = user()->id();
        });
    }
    // Create the resoource
    //Display the specified resource.
    public function show(Department $department)
    {
        // In an admin panel, I usually don't need this method. It's often more efficient to
        // show the department data in the edit view.
    }

    //Show the form for editing the specified resource.
    public function edit($id)
{
    $department = Department::findOrFail($id);

    return view('departments.edit', compact('department'));
}

    //Update the specified resource in storage.
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
         'name' => 'required|max:255',
         'head' => 'required|max:50',
        ]);
        Department::whereId($id)->update($validatedData);

        return redirect('/departments')->with('success', 'Department is successfully updated');
    }

    //Remove the specified resource from storage.
    public function destroy(department $department)
    {
        $department->delete();

        return redirect()->route('departments.index')
                        ->with('success','Department deleted successfully');
    }
}

мой просмотр журнала создания:

<form role="form" class="registration-form" action="{{ route('logs.store')}}">
                    <fieldset>
                        <div class="form-top">
                            <div class="form-top-left">
                                <h3><span><i class="fa fa-calendar-check-o" aria-hidden="true"></i></span>Enter the Duty log for the Technical Department
                                </p>
                            </div>
                        </div>
                        <div class="form-bottom">
                            <div class="form-group">
                                <input type="text" name="title" placeholder="Log Title" class="form-control" id="title" required>
                            </div>

                            <div class="form-group">
                                <input type="text" name="comment" placeholder="Log Details" class="form-control" id="comment" required>
                            </div>
                            <button type="button" class="btn btn-next">Next</button>
                        </div>
                    </fieldset>

.. ....... для остальных 7.

затем последний

<fieldset>
                        <div class="form-top">
                            <div class="form-top-left">
                                <h3><span><i class="fa fa-calendar-check-o" aria-hidden="true"></i></span>Enter the Duty log for the I.T. Department
                                </p>
                            </div>
                        </div>
                        <div class="form-bottom">
                            <div class="form-group">
                                <input type="text" name="title" placeholder="Log Title" class="form-control" id="title" required>
                            </div>

                            <div class="form-group">
                                <input type="text" name="comment" placeholder="Log Details" class="form-control" id="comment" required>
                            </div>
                            <button type="button" class="btn btn-previous">Previous</button>
                            <button type="submit" class="btn">Submit</button>
                        </div>
                    </fieldset>

вот мой обработчик форм jquery:


$(document).ready(function () {
$('.registration-form fieldset:first-child').fadeIn('slow');

$('.registration-form input[type="text"]').on('focus', function () {
    $(this).removeClass('input-error');
});

// next step
$('.registration-form .btn-next').on('click', function () {
    var parent_fieldset = $(this).parents('fieldset');
    var next_step = true;

    parent_fieldset.find('input[type="text"],input[type="email"]').each(function () {
        if ($(this).val() == "") {
            $(this).addClass('input-error');
            next_step = false;
        } else {
            $(this).removeClass('input-error');
        }
    });

    if (next_step) {
        parent_fieldset.fadeOut(400, function () {
            $(this).next().fadeIn();
        });
    }

});

// previous step
$('.registration-form .btn-previous').on('click', function () {
    $(this).parents('fieldset').fadeOut(400, function () {
        $(this).prev().fadeIn();
    });
});

// submit
$('.registration-form').on('submit', function (e) {

    $(this).find('input[type="text"],input[type="email"]').each(function () {
        if ($(this).val() == "") {
            e.preventDefault();
            $(this).addClass('input-error');
        } else {
            $(this).removeClass('input-error');
        }
    });

});


});

Я попытался зациклить этот отделформа, но получил смещение -1. ​​

Я все еще новичок в Laravel и мне нужна вся помощь, которую я могу получить в этом. заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...