Laravel как вставить данные в 2 таблицы? - PullRequest
0 голосов
/ 19 апреля 2020

модель моего пользователя

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'role_id', 'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Модель больницы


namespace App;

use Illuminate\Database\Eloquent\Model;

class Hospital extends Model
{
    /**
     * @var String $table;
     */
    protected $table = 'hospitals';

    /**
     * @var Array $fillable;
     */

    protected $fillable = [
        'user_id', 'companyname', 'adress', 'postalcode', 'residence',
        'phonenumber', 'mailadress'
    ];
}

Контроллер больницы


namespace App\Http\Controllers;

use App\Http\Controllers\RolesController;
use App\Permission;
use App\Role;
use App\RolesPermissions;
use App\User;
use Illuminate\Http\Request;
use Auth;
use App\Hospital;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class HospitalController extends Controller
{
    public function __construct()
    {
        $this->roles = new RolesController();
    }

    public function index()
    {
        $permission = $this->roles->getUserRole(28);
        if ($permission->Permissions[0]->name == 'index_hospital' && $permission->confirmed == 1) {
            $hospitals = Hospital::get();
            return view('hospitals.index', compact('hospitals'));
        } else {
            return redirect('epd')->with('status', 'U heeft niet de juiste bevoegdheden');
        }
    }

    public function create()
    {
        $hospitals = Hospital::get();
        return view('hospitals.create', compact('hospitals'));
    }


    public function store(User $user, Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255|unique:users',
            'password' => 'required|min:8',
        ]);

        $user = User::create($this->transformForm($request));
        return redirect()->route('hospitals.update', ['id' => $user->id]);

    }

    public function update(Hospital $hospitals)
    {
        if(Hospital::find($hospital->id)){
            $hospital->update();
        }
        else{
            Hospital::create([
                'user_id' => $user,
                'companyname' => $request->input('companyname'),
                'adress' => $request->input('adress'),
                'postalcode' => $request->input('postalcode'),
                'residence' => $request->input('residence'),
                'phonenumber' => $request->input(),
                'mailadress' => $request->input()]);
        }
    }

    public function put(Request $request, RolesPermissions $roles)
    {

    }

    private function transformForm($request)
    {
        return [
            'role_id' => 11,
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => Hash::make($request['password']),
        ];
    }
}

create_blade. php


@section('content')

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Ziekenhuis aanmaken</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Ziekenhuis</a></li>
                        <li class="breadcrumb-item active">Create</li>
                    </ol>
                </div>
            </div>
        </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <form action="{{ route('epd.hospitals.store') }}" method="post" >
                <div class="card card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">Gebruiker aanmaken</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="email">E-mailadres</label>
                                        <input id="email" type="email"  name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Enter email" required autocomplete="email" autofocus>
                                        @error('email')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label for="name">Naam</label>
                                        <input id="name" type="text" class="form-control  @error('name') is-invalid @enderror" name="name" placeholder="Naam" required autocomplete="name">
                                        @error('name')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label for="password">Wachtwoord</label>
                                        <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" placeholder="Wachtwoord" required autocomplete="new-password">
                                        @error('password')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label>Toegewezen rol</label>
                                        <select class="custom-select" disabled>
                                            <option>Ziekenhuis</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <br>
                    </div>
                    <!-- /.card-body -->
                </div>
                <!-- /.card -->
                <br>
                <!-- general form elements disabled -->
                <div class="card card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">Gegevens invoeren</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="bedrijfsnaam">Bedrijfsnaam</label>
                                        <input type="text" class="form-control" name="companyname" placeholder="Bedrijfsnaam" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Adres</label>
                                        <input type="text" class="form-control" name="adress" placeholder="Adres" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Postcode</label>
                                        <input type="text" class="form-control" name="postalcode" placeholder="Postcode" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Vestigingsplaats</label>
                                        <input type="text" class="form-control" name="residence" placeholder="Vestigingsplaats" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Telefoonnummer</label>
                                        <input type="text" class="form-control" name="residence" placeholder="Telefoonnummer" required>
                                    </div>
                                </div>
                            </div>
                            <br>
                    </div>
                    <!-- /.card-body -->
                    <div class="card-footer">
                        @csrf
                        <input type="submit" name="submit" class="btn btn-primary" value="Ziekenhuis opslaan">
                    </div>
                </div>
                <!-- /.card -->
            </form>
        </div>
        <!-- /.col (right) -->
        </section>
</div>
<!-- /.row -->
@endsection

На данный момент это рядом с моим create.blade. php код, который у меня есть. Намерение заключается в том, что, когда администратор хочет создать больницу. В дополнение к больнице, пользователь также создан. Когда пользователь создан, идентификатор созданного пользователя должен быть указан в таблице больниц. Однако я понятия не имею, как лучше к этому подойти. Есть ли у кого-нибудь советы, что я делаю неправильно и что я делаю лучше, и что мне нужно сделать, чтобы достичь этого результата.

Create_blade. php

<form action="{{ route('epd.hospitals.store') }}" method="post" >
                <div class="card card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">Gebruiker aanmaken</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="email">E-mailadres</label>
                                        <input id="email" type="email"  name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Enter email" required autocomplete="email" autofocus>
                                        @error('email')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label for="name">Naam</label>
                                        <input id="name" type="text" class="form-control  @error('name') is-invalid @enderror" name="name" placeholder="Naam" required autocomplete="name">
                                        @error('name')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label for="password">Wachtwoord</label>
                                        <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" placeholder="Wachtwoord" required autocomplete="new-password">
                                        @error('password')
                                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                        </span>
                                        @enderror
                                    </div>
                                    <div class="form-group">
                                        <label>Toegewezen rol</label>
                                        <select class="custom-select" disabled>
                                            <option>Ziekenhuis</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <br>
                    </div>
                    <!-- /.card-body -->
                </div>
                <!-- /.card -->
                <br>
                <!-- general form elements disabled -->
                <div class="card card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">Gegevens invoeren</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="bedrijfsnaam">Bedrijfsnaam</label>
                                        <input type="text" class="form-control" name="companyname" placeholder="Bedrijfsnaam" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Adres</label>
                                        <input type="text" class="form-control" name="adress" placeholder="Adres" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Postcode</label>
                                        <input type="text" class="form-control" name="postalcode" placeholder="Postcode" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Vestigingsplaats</label>
                                        <input type="text" class="form-control" name="residence" placeholder="Vestigingsplaats" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Telefoonnummer</label>
                                        <input type="text" class="form-control" name="residence" placeholder="Telefoonnummer" required>
                                    </div>
                                </div>
                            </div>
                            <br>
                    </div>
                    <!-- /.card-body -->
                    <div class="card-footer">
                        @csrf
                        <input type="submit" name="submit" class="btn btn-primary" value="Ziekenhuis opslaan">
                    </div>
                </div>
                <!-- /.card -->
            </form>

1 Ответ

1 голос
/ 19 апреля 2020

Первое, что вам НЕ нужно вводить User модель в ваше store действие, подобное этому

public function store(User $user, Request $request)

Вы можете использовать транзакцию, подобную следующей, в вашем hospital контроллере store действие

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|max:255|unique:users',
        'password' => 'required|min:8',
    ]);

    DB::transaction(function () use($request){
        // $user = User::create($this->transformForm($request)); 

        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => $request->input('password'),
        ]);

        // update or insert here
        Hospital::Create([
            'user_id' => $user->id,
            'companyname' => $request->input('companyname'),
            'adress' => $request->input('adress'),
            'postalcode' => $request->input('postalcode'),
            'residence' => $request->input('residence'),
            // 'phonenumber' => $request->input(), //missing in your form
            // 'mailadress' => $request->input() // missing in your form
        ]);
    });

    return //redirecto to a success page or somewhere else
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...