LoginSignup
jankenpon0205
@jankenpon0205 (002 ruru)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ユーザー名を表示させたい

解決したいこと

現在、簡単な投稿サイトを作っているのですが、ユーザー名の所が表示されません。
元々はIDが表示されるようにしたていた(1枚目の写真)のですが、ユーザー名に切り替えたら、表示されず2枚目の写真のようなエラーを起こしてしまいました。気になるのでどうやればユーザー名が表示されるか知りたいので教えていただきたいです。

使用しているバージョンは以下のとおりです。

・PHP 8.2.4
・laravelcollective/html (v6.4.1)
・node v20.12.0
・npm 10.5.0

私の説明不足で大変申し訳ありませんが、もしこれだけではわからないという方がいればご指摘の程お願いします。

image.png

発生している問題・エラー

Undefined property: stdClass::$name (View: C:\xampp\htdocs\project_CRUD\Laravel\resources\views\posts\index.blade.php)

image.png

migrations/2024_03_03_132252_posts.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\DB;

class Posts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        
        Schema::create('posts', function (Blueprint $table) {
 
            $table->increments('id');

            $table->string('name');

            $table->integer('user_id');
             
            $table->string('post', 255);
             
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
             
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
             
            });
             

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

migrations/2014_10_12_000000_create_users_table.php

<?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->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

views/post/index.blade.php

@extends('layouts.app')
@section('content')
<div class='container'>

<p class="pull-right"><a class="btn btn-success" href="/create-form">投稿する</a></p>
 
<h2 class='page-header'>投稿一覧</h2>


 
<table class='table table-hover'>
 
<tr>
 
<th>ユーザー名</th>
 
<th>投稿内容</th>
 
<th>投稿日時</th>

<th></th>
 
</tr>

 
@foreach ($lists as $list)
 
<tr>
 
<td>{{ $list->name }}</td>
 
<td>{{ $list->post }}</td>
 
<td>{{ $list->created_at }}</td>

<td><a class="btn btn-primary" href="/post/{{ $list->id }}/update-form">編集</a></td>

<td><a class="btn btn-danger" href="/post/{{ $list->id }}/delete" onclick="return confirm('こちらの投稿を削除してもよろしいでしょうか?')">削除</a></td>
 
</tr>
 
@endforeach
 
</table>
 
</div>
 
@endsection
0

2Answer

記載のコードだけでは変数$lists$listの中身が不明なので、解決策を提示することはできません。
関連するControllerやModelのコードが必要です。

またユーザ名というのはusersテーブルのnameカラムの情報でしょうか?

0Like

Comments

  1. @jankenpon0205

    Questioner

    ご指摘ありがとうございます。
    おそらくこれとこれが関係していると思いますので見ていただければ幸いです。

    また、ユーザー名の情報の件ですが、写真のようになっていますのでその認識で合っています。

    image.png

    Http/Controller/PostsController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    use Illuminate\Support\Facades\DB; 
     
    class PostsController extends Controller
    
    {
        
       
    public function index()
     
    {
     
    $list = DB::table('posts')->get();
     
    return view('posts.index',['lists'=>$list]);
     
    }
    
    public function createForm()
    {
    return view('posts.createForm');
    }
     
    public function create(Request $request)
     
    {
     
    $post = $request->input('newPost');
     
    DB::table('posts')->insert([
     
    'post' => $post
     
    ]);
     
    return redirect('/index');
     
    }
    
    public function updateForm($id)
     
    {
     
    $post = DB::table('posts')
     
    ->where('id', $id)
     
    ->first();
     
    return view('posts.updateForm', ['post' => $post]);
     
    }
    
    public function update(Request $request)
     
    {
     
    $id = $request->input('id');
     
    $up_post = $request->input('upPost');
     
    DB::table('posts')
     
    ->where('id', $id)
     
    ->update(
     
    ['post' => $up_post]
     
    );
     
    return redirect('/index');
     
    }
    
    public function delete($id)
     
    {
     
    DB::table('posts')
     
    ->where('id', $id)
     
    ->delete();
     
     
     
    return redirect('/index');
     
    }
     
    public function __construct()
     
    {
     
    $this->middleware('auth');
     
    }
    }
    

    app/Models/User.php

    <?php
    
    namespace App\Models;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Sanctum\HasApiTokens;
    
    class User extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array<int, string>
         */
        protected $fillable = [
            'name',
            'email',
            'password',
        ];
    
        /**
         * The attributes that should be hidden for serialization.
         *
         * @var array<int, string>
         */
        protected $hidden = [
            'password',
            'remember_token',
        ];
    
        /**
         * The attributes that should be cast.
         *
         * @var array<string, string>
         */
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    }
    
  2. 追加情報ありがとうございます。

    $list->nameはpostsテーブルのnameカラムを参照しているように見えます。
    postsテーブルにnameカラムは作成されていますか?

  3. @jankenpon0205

    Questioner

    ご返信ありがとうございます。
    旧Twitterのように「ログインしたユーザー名がこのようなpostした」という表示にしたいので、上記のようにしました。
    確認したところ、写真のようになっていました。
    「migrations/2024_03_03_132252_posts.php」にnameカラムを追加しているのですが、このファイル以外ですか?

    image.png

  4. 状況が分かってきました。
    おそらくマイグレーションファイルに後から$table->string('name')を追加したのではないでしょうか。
    スクリーンショットを見るとnameカラムがないので、その変更がデータベースに反映されていないのでしょう。
    よって取得したデータにもnameの情報が無いので「Undefined property: stdClass::$name」というエラーが発生しているのだと思います。

    直接的な解決方法は、カラムの追加をデータベースに反映させることです。
    既存のマイグレーションファイルを変更したのであれば、いったんマイグレーションをロールバック(テーブルを削除)して再度マイグレーションを実行することになると思います。

    旧Twitterのように「ログインしたユーザー名がこのようなpostした」という表示にしたいので、上記のようにしました。

    根本的な部分として、ユーザテーブルがあるのに記事テーブルにユーザ名を直接追加するようなことは、通常はやらないので特殊な設計に見えます。
    しかしながら、いったんは「postsテーブルのnameカラムを参照する」という方向で回答しています。

  5. @jankenpon0205

    Questioner

    回答して頂きありがとうございます。
    マイグレーションを写真のようにロールバックし、修正した後「php artisan migrate」を実行しましたが、エラーが起きてしまいました。
    写真のようなやり方は間違っていたのでしょうか?

    ちなみに順番は2枚目の写真のとおりです。

    image.png

    image.png

  6. エラーメッセージからすると接続エラーのようなので、マイグレーション自体が原因ではないように思えます。
    何度やっても同じエラーが出るのでしょうか?

  7. @jankenpon0205

    Questioner

    ご返信が遅くなりすみません。
    もう一回再実行したらうまくいきましたが、投稿が出来なくなりました。
    エラーが起こっているファイルは一度もいじったことが無いファイルです。
    ユーザー名を表示させるコマンド実行する前は投稿できたのですが、なぜこのようなことが起きるのか御存知であれば教えていただきたいです。
    また、これだけではわからないのであれば、ご指摘お願いします。

    image.png

    image.png

    image.png

  8. もう一回再実行したらうまくいきましたが、投稿が出来なくなりました。

    正常に実行できたのであればnameカラムが作成されているのだと思います。
    そしてnameカラムはNOT NULL制約が付いているので、NULLの状態にすることができません。
    しかし、記載のコードはnameの値を設定せずにデータを作成しているのでエラーが発生していると思われます。

  9. @jankenpon0205

    Questioner

    すみません、勉強不足で申し訳ないのですが、nameの値とはどこを指していますか?
    教えていただければ幸いです。
    ちなみに、確認したところnameカラムは追加できていました。

    image.png

  10. nameの値とはどこを指していますか?

    コントローラーのデータを追加する処理についてです。
    記載のコードから変更していないのであれば、追加したnameカラムやuser_idカラムに対して値を設定していない状態だと思います。

    Http/Controller/PostsController.php
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    use Illuminate\Support\Facades\DB; 
     
    class PostsController extends Controller
    {
    
    // ...
     
    public function create(Request $request)
     
    {
     
    $post = $request->input('newPost');
     
    DB::table('posts')->insert([
     
    'post' => $post
     
    ]);
    
    // ...
    
    }
    
  11. @jankenpon0205

    Questioner

    これを真似てcreateメソッドにnameカラムを追加すればいいのでしょうか?
    また、その際にweb.phpにルーティングの設定をする必要がありますか?
    以下のコードがweb.phpです。

    Laravel/routes/web.php

    <?php
    
    use Illuminate\Support\Facades\Route;
    
    use App\Http\Controllers\PostsController;
    
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
    
    Route::get('/', function () {
        return view('welcome');
    });
    
    // Route::get('hello', function(){
     
    //     echo 'Hello World!!';
    
    // });
    
    Route::get('hello', [PostsController::class, 'hello']);
    
    Route::get('index', function(){
        return view('index');
    });
    
    Route::get('index', [PostsController::class, 'index']);
    
    Route::get('/create-form', [PostsController::class, 'createForm']);
    
    Route::post('post/create', [PostsController::class,
    'create']);
    
    Route::get('post/{id}/update-form', [PostsController::class, 'updateForm']);
    
    Route::post('post/update', [PostsController::class,
    'update']);
    
    Route::get('post/{id}/delete', [PostsController::class, 'delete']);
    Auth::routes();
    
    Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
    
  12. 発生したエラーについてデータベースの理解が必要ですが、それについては学習されている状況でしょうか?
    データベースがどのようなものであるか理解し、同時に、Laravelからどのように操作しているのかを理解する必要があります。

    改めて発生したエラーについて説明します。

    Field name doesn't have a default value

    テーブルへのデータの挿入(INSERT)は、テーブル定義に沿ったデータにする必要があります。エラーメッセージを直訳すると「フィールドnameにデフォルト値がない」となりますが、値を設定すべきカラムに明示的に値が指定されていないことを示しています。

    詳しくは下記の記事を参照してください。
    ただしLaravelを使用しているので、解決策を直接使うことはできないことに注意してください。

根本的な間違いは「参考にしてる情報を間違ってる」
初心者は本が間違ってるかどうかも判断できないので間違ってる本を正しいと思い込む。
XAMPPとかphpMyAdminとか使ってる時点で「どこが」ではなく「全部間違ってる」

createでは$postしか保存してなくて「postsのname」も「Userのname」もない。$nameを表示しようとしてもどこにもないからできない。

public function create(Request $request)
{
    $post = $request->input('newPost');

    DB::table('posts')->insert([
        'post' => $post
    ]);
 
    return redirect('/index');
}

「Laravelの基本機能」さえも全く理解せずに使ってるので改善しようがない。
Laravelのドキュメントを全ページ読むのがまずやること。
https://laravel.com/docs/11.x/installation

DB::table('posts')なんて使うことは一切なくEloquentしか使わない。

0Like

Your answer might help someone💌