Есть ли способ получить идентификатор в методе создания в laravel - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь передать иностранный напрямую в мой метод создания

В проекте, над которым я работаю, у меня есть два разных пользователя. Первая - это ферма, которая может создать животное. Вторая - это клиника, которая может прикрепить к животному некоторые сведения о клинике, показывающие, было ли животное вакцинировано или нет. В моей таблице сведений о клинике у меня есть внешний ключ животного, но я не знаю, как передать этот ключ методу создания

Вот мой контроллер Клиники

<?php

namespace App\Http\Controllers;

use App\Animal;
use App\Clinic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ClinicController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

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

    public function index()
    {
        $user = Auth::user();
        $animal = Animal::all();
        return view('clinic.index', compact('user', 'animal'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @param $id
     * @return void
     */
    public function create($id)
    {
        $user = Auth::user();
        $animal = Animal::query()->findOrFail($id);
        $clinic = new Clinic();

        return view('clinic/create', compact('user', 'animal', 'clinic'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $animal = Animal::query()->findOrFail($id);
        return view('clinic.show', compact('animal'));
    }

    /**
     * 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)
    {
        //
    }
}

Мойclinic index.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header"><h3>Clinic Details Dashboard</h3></div>

                    <div class="card-body">
                        @if (session('status'))
                            <div class="alert alert-success" role="alert">
                                {{ session('status') }}
                            </div>
                        @endif

                        You are logged in! {{ $user->name}}
                            <hr>
                            <center><h3>Animals</h3></center>
                            <hr>
                            @foreach($animal as $animal)
                                <div class="row">
                                    <div class="col-2">{{ $animal->id }}</div>
                                    <div class="col-4"><a href="/clinic/{{ $animal->id }}">{{ $animal->type->category }}</a></div>
                                    <div class="col-2">{{ $animal->user->name }}</div>
                                    <div class="col-4">{{ $animal->created_at }}</div>
                                </div>
                            @endforeach

                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

моя клиника show.blade.php Здесь я хотел бы передать идентификатор животного методу create, но я не знаю как. Даже моя кнопка ссылки не идет в представление создания

@extends('layouts.app')
@section('title', 'Details for animal ')
@section('content')


    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <center><h3>Details for the animal</h3></center>
                    </div>
                    <div class="card-body">
                        <div class="col-12">
                            <p><strong>Id: </strong>{{ $animal->id }}</p>
                            <p><strong>Animal: </strong>{{ $animal->type->category }}</p>
                            <p><strong>Farm: </strong>{{ $animal->user->name }}</p>
                            <p><strong>Gender: </strong>{{ $animal->gender }}</p>
                            <p><strong>Place Of Birth: </strong>{{ $animal->placeOfBirth }}</p>
                            <p><strong>Date: </strong>{{ $animal->created_at }}</p>
                        </div>
                        <div class="col-md-8 offset-md-4">
                            <a href="create">
                                <button type="button" class="btn btn-primary">
                                    Attach Clinic Detail
                                </button>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

клиника create.blade.php Это представление все еще как-то пусто

@extends('layouts.app')
@section('title', 'Add Clinical Details')
@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">New Animal</div>

                    <div class="card-body">
                        <form action="{{ url('clinic') }}" method="POST">


                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Ответы [ 2 ]

0 голосов
/ 21 октября 2019

Вы можете использовать метод insertGetId () для получения последнего созданного идентификатора после метода сохранения.
https://laravel.com/api/5.0/Illuminate/Database/Query/Builder.html#method_insertGetId

$id = DB::table('posts')->insertGetId(
    array('title' => 'my post title', 'body' => 'my post body')
);                                                              
0 голосов
/ 21 октября 2019

Вы можете просто добавить параметр в ваш метод, например так:

public function create($id, $foreignKeyId) {
    // ... to something 
}

Для этого вам нужно будет передать id в качестве скрытого ввода.

Вы также можете попытаться создатьотношение, таким образом вам не нужно добавлять ForeignKey в качестве параметра. Вы можете просто получить доступ к Foreign_key, используя указанную модель ORM.

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