質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

Blade

Bladeとは、 PHPフレームワークのLaravelで使用することができるテンプレートエンジンです。テンプレートの継承とエスケープ機能を提供します。

Q&A

0回答

875閲覧

ユーザーがRegisterをクリックし新規登録を行なったら、自動的に空のプロフィールが作られるようにしたい。

nkkn-prog

総合スコア0

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

ログイン

ログインは、ユーザーがコンピューターシステムにアクセスするプロセスの事を呼びます。

Blade

Bladeとは、 PHPフレームワークのLaravelで使用することができるテンプレートエンジンです。テンプレートの継承とエスケープ機能を提供します。

0グッド

0クリップ

投稿2022/01/10 10:02

現在php・laravel歴1ヶ月のエンジニアで、初投稿です。
分かりにくい箇所がございましたらコメントいただければと思います。
以下質問内容です。

###前提
Laravelでwebアプロケーションを作成しており、
Laravel uiでログイン機能を導入し、make:authコマンドで認証機能を実装しています。

 
###現状
ユーザーは新規登録後、authで設定されているhome画面('/home')に遷移し、「プロフィールを作成していない方はこちら」をクリックするとプロフィール作成画面('/profile/create')に遷移、そして「プロフィールを作成していない方はこちら」をクリックするとホーム画面('/')に遷移するように設定しています。

ちなみにホーム画面('/')には3つの項目があり、順番に、
①「他の人のプロフィールを見る」を押すと'/index'、
②「自分のプロフィールを見る」を押すと、'/profile/{{$profile->id}}/show'、
③「まだプロフィールを作成していない方はこちら」を押すと、'/profile/create'に遷移します。

profilesテーブルに外部キーuser_idの設定をすることでプロフィールを管理しようと考え、usersテーブルを主テーブル、profilesテーブルを従テーブルとして1対1のリレーションの設定を行い、usersテーブルのidとprofilesテーブルのidの紐付けを行ってみました。しかし、user_idはcreate.blade.phpでformタグから送信される際に設定されるため、プロフィールを作成していないユーザーにuser_idが発行されず、user_idが入っていないのでホーム画面('/')遷移時にエラーが出てしまいます。(エラー画像参照)

そのため外部キー使うのではなく、ユーザーが新規登録後、自動的に空のプロフィールが作成されるように設定したいです。

###実現したいこと
ユーザーがRegisterをクリックし、「上記のメールアドレスで登録」を押して新規登録を行なったら、自動的に空のプロフィールが作られるようにしたい。
イメージ説明

該当のソースコード

UserController

<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use App\Http\Requests\ProfileRequest; use App\Http\Requests\SearchRequest; use App\User; use App\Profile; use App\Instrument; use App\Genre; use App\Prefecture; use App\Image; use Storage; class UserController extends Controller { public function index(User $user, Profile $profile, Instrument $instrument, Genre $genre, Prefecture $prefecture) { return view('general/index')->with([ 'profiles'=>$profile->get(), 'instruments'=>$instrument->get(), 'genres'=>$genre->get(), 'prefectures'=>$prefecture->get(), ]); } public function welcome() { $user = Auth::user(); $profile = $user->profile; return view('general/welcome')->with([ 'profile'=>$profile, ]); } public function create(User $user, Profile $profile, Instrument $instrument, Genre $genre, Prefecture $prefecture) { return view('profile/create')->with([ 'instruments'=>$instrument->get(), 'genres'=>$genre->get(), 'prefectures'=>$prefecture->get(), ]); } public function store(ProfileRequest $request, Profile $profile, Image $image) { //s3へのファイルアップロード開始 $profile_image = $request->file('image'); $path = Storage::disk('s3')->putFile('myprefix', $profile_image, 'public'); $image->image_path = Storage::disk('s3')->url($path); $image->save(); //s3へのファイルアップロード終了 //プロフィール内容の取得開始 $input_profile = $request['profile']; $input_profile += ['user_id' => Auth::user()->id]; $input_profile += ['image_id' => $image->id]; $input_instruments = $request['instruments_array']; $input_genres = $request['genres_array']; $profile->fill($input_profile) ->save(); //プロフィール内容の取得終了 //プロフィール内容の保存開始 $profile->fill($input_profile) ->save(); $profile->instruments()->attach($input_instruments); $profile->genres()->attach($input_genres); //プロフィール内容の保存終了 //自身のプロフィール画面へリダイレクト return redirect('/profile/'.$profile->id.'/show'); }

web.php

<?php Route::group(['middleware'=>'auth'], function(){ Route::get('/', 'UserController@welcome'); Route::get('/profile/{profile}/show', 'UserController@show'); Route::post('/profile/{profile}/show', 'UserController@show'); Route::get('/index', 'UserController@index'); Route::get('/profile/create', 'UserController@create'); Route::post('/profile/complete', 'UserController@store'); });

create.blade.php

<!DOCTYPE html> @extends('layouts.app') @section('content') <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>create.blade.php</title> </head> <body> {{Auth::user()->name}}さんのページ <!--プロフィール作成--> <h1>プロフィールを作成しよう</h1> <form action ="/profile/complete" method='POST' enctype="multipart/form-data"> @csrf <div class='nickname'> <h2>ニックネーム</h2> <input type='text' name="profile[nickname]" placeholder='ニックネーム' value="{{ old('profile.nickname') }}" /> <p class="title__error" style="color:red">{{ $errors->first('profile.nickname') }}</p> </div> <div class ='sex'> <h2>性別</h2> <input type="radio" name="profile[sex]" value='男性'>男性</input> <input type="radio" name="profile[sex]" value='女性'/>女性</input> <input type="radio" name="profile[sex]" value='回答したくない'/>回答したくない</input> <p class="title__error" style="color:red">{{ $errors->first('profile.sex') }}</p> </div> <div class ='age'> <h2>年齢</h2> <input type='text' name="profile[age]" placeholder='年齢' value='{{ old('profile.age') }}' /> <p class="title__error" style="color:red">{{ $errors->first('profile.age') }}</p> </div> <div class ='prefecture'> <h2>住んでいる都道府県</h2> <select name='profile[prefecture_id]'> @foreach($prefectures as $prefecture) <option hidden>選択してください</option> <option value="{{$prefecture->id}}">{{$prefecture->name}}</option> @endforeach <p class="title__error" style="color:red">{{ $errors->first('profile.prefecture_id') }}</p> </select> </div> <div class ='instument'> <h2>出来る楽器</h2> @foreach($instruments as $instrument) <label> <input type='checkbox' value="{{$instrument->id }}" name='instruments_array[]'> {{$instrument->name}} </input> </label> @endforeach </div> <div class ='genre'> <h2>音楽ジャンル</h2> @foreach($genres as $genre) <label> <input type='checkbox' value="{{$genre->id }}" name='genres_array[]'> {{$genre->name}} </input> </label> @endforeach </div> <div class ='musical_experience'> <h2>楽器歴</h2> <input type='text' name="profile[musical_experience]" placeholder='◯年以上' value="{{ old('profile.musical_experience') }}"/> <p class="title__error" style="color:red">{{ $errors->first('profile.musical_experience') }}</p> </div></br> <div class ='message'> <h2>ひとこと</h2> <textarea name="profile[message]" row="3" colm="30" placeholder="ひとこと">{{ old('profile.message') }}</textarea> <p class="title__error" style="color:red">{{ $errors->first('profile.message') }}</p> </div> <!--画像登録--> <input type="file" name="image"/> <input type='submit' value='プロフィールを作成する'/> </form> </body> </html> @endsection

usersテーブル

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email'); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }

profilesテーブル

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProfilesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('profiles', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id'); $table->string('nickname'); $table->string('sex'); $table->integer('age'); $table->integer('prefecture_id'); $table->string('musical_experience'); $table->string('message'); $table->string('image_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('profiles'); } }

試したこと

RegisterControllerのcreate処理(ユーザーを作成する処理)の中に、profileを作成するような処理を書きましたが、上手くいきませんでした。

補足情報(FW/ツールのバージョンなど)

使用言語:PHP 8.0.13
使用フレームワーク: Laravel 6.20.42

###エラー画像
イメージ説明

ご教授いただけると幸いです。
よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoboki

2022/01/14 00:06 編集

welcome.blade.phpでエラーが起きているのにそのファイルのソースコードがないので、いまいちどんなエラーを解消したいのかわからないのと「上記のメールアドレスで登録」を押した際のルートもわかりません。 それにUserControllerのcreateメソッドの内容的に、ProfileControllerに書くべきものだと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問