Answer the question
In order to leave comments, you need to log in
How to get username by id (Laravel)?
Hello.
Created tables:
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name')->nullable();
$table->string('nickname')->nullable();
$table->string('avatar')->default('default.jpg');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('role', 50)->default('guest');
$table->timestamps();
});
}
public function up(): void
{
Schema::create('blog_posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('author_id');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->string('thumbnail')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->string('tdk_title')->nullable();
$table->text('tdk_description')->nullable();
$table->string('tdk_keywords')->nullable();
$table->unsignedBigInteger('view_count')->default(0);
$table->boolean('is_published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->softDeletes();
// Foreign keys
$table->foreign('author_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('category_id')
->references('id')
->on('blog_categories')
->onDelete('cascade');
$table->index('is_published');
});
}
$table->foreign('author_id')
->references('id')
->on('users')
->onDelete('cascade');
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id', 'id');
}
Answer the question
In order to leave comments, you need to log in
Error in understanding how model relationships work in Laravel, I advise you to read the documentation .
$post->user->first_name
When I call $post->author_id - I get the user's id. Tell me, where did you go wrong?
//Вместо
$post->author_id->first_name
//Должно быть
$post->user->first_name
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question