@person98

Не загружается файлы и не записывается в базу?

Вот создал Laravel проект
Есть у меня 2 Модельки Candidate с его данными и CandidateFiles для хранения имен файлов и candidate_id!
Сам Candidate создается и записывает все данные в базу! А вот CandidateFiles не записывается, и файлы тоже не хранятся! Cвязи в модельках проставил и в миграциях связи тоже указал!
Запрос отправляю с Postman:
5e9a9f5f48e2d361938201.png
Контроллер :
namespace App\Http\Controllers\Api\V1\Home;

use App\Entity\Candidate\Candidate;
use App\Entity\Candidate\CandidateFiles;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    public function getAllFaculties()
    {
        return [
            'name' => 'Board Api'
        ];
    }

    public function createCandidate(Request $request)
    {
        $newCandidate = Candidate::createNewCandidate(
            $request['candidateName'],
            $request['candidateLastName'],
            $request['candidatePatronymic'],
            $request['candidatePhoneNumber'],
            $request['departmentId'],
            $request['candidateEmail']
        );

        foreach ($request->file('documents') as $document) :
            $fileName = Str::random(10) . $document->extension();

            $document->storeAs('uploads/' . $request['departmentId'], $fileName);

            CandidateFiles::create([
                'candidate_id' => $newCandidate->id,
                'candidate_document_file' => $fileName
            ]);
        endforeach;

        return response()->json(['message' => $request['candidateName'] . ' ' . $request['candidatePatronymic']. ' мы приняли вашу заявку! Будем сообщать вам о всех изменениях статуса вашей заявки на конкурс через указанный вами email и номера телефона!'], Response::HTTP_CREATED);
    }
}

Модель Candidate:
namespace App\Entity\Candidate;

use Illuminate\Database\Eloquent\Model;

class Candidate extends Model
{
    protected $fillable = ['candidate_name', 'candidate_last_name', 'candidate_patronymic', 'candidate_phone_number', 'department_id', 'candidate_email'];

    protected $guarded = [];

    public function candidateFiles()
    {
        return $this->hasMany(CandidateFiles::class,'candidate_id','id');
    }

    public static function createNewCandidate($candidateName, $candidateLastName,  $candidatePatronymic, $candidatePhoneNumber, $departmentName, $candidateEmail)
    {
        return static::create([
            'candidate_name' => $candidateName,
            'candidate_last_name' => $candidateLastName,
            'candidate_patronymic' => $candidatePatronymic,
            'candidate_phone_number' => $candidatePhoneNumber,
            'department_id' => $departmentName,
            'candidate_email' => $candidateEmail,
        ]);
    }
}

Модель CandidateFiles:
namespace App\Entity\Candidate;

use Illuminate\Database\Eloquent\Model;

class CandidateFiles extends Model
{
    public function candidate()
    {
        return $this->belongsTo(Candidate::class);
    }
}

Миграция CreateCandidatesTable:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCandidatesTable extends Migration
{
    public function up()
    {
        Schema::create('candidates', function (Blueprint $table) {
            $table->id();
            $table->string('candidate_name');
            $table->string('candidate_last_name',255);
            $table->string('candidate_patronymic',255)->nullable();
            $table->string('candidate_phone_number',255);
            $table->string('candidate_avatar',255);
            $table->integer('department_id')->references('department_id')->on('departments');
            $table->string('candidate_email')->unique()->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('candidates');
    }
}

Миграция CreateCandidateFilesTable:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCandidateFilesTable extends Migration
{
    public function up()
    {
        Schema::create('candidate_files', function (Blueprint $table) {
            $table->id();
            $table->integer('candidate_id')->references('id')->on('candidates');
            $table->string('candidate_document_file',255)->unique()->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('candidate_files');
    }
}
  • Вопрос задан
  • 101 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы