I'm developing a Laravel 9 web application with two tables (users
and feedbacks
) that use a foreign key named username
Make a connection. A user can have a lot of feedback. As far as I know, if I get the user's details, the data also contains relevant feedback. My problem is that the user data is being fetched correctly but it comes with all the feedback instead of being connected to that specific user's feedback. Laravel executes such a query.
select * from `feedback` where `feedback`.`username` = 0 and `feedback`.`username` is not null
As I understand it, 0 should be replaced with the user's username. Is there something wrong here?
Feedback
Model-
class Feedback extends Model { use HasFactory; //One single user can have many feedbacks. public function user() { return $this->belongsTo(User::class); } }
User
Model-
class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'username', 'gender', 'email', 'password', 'is_admin', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', 'is_admin', ]; protected $primaryKey = 'username'; public function feedbacks() { return $this->hasMany(Feedback::class, 'username'); } /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }
create_users_table
Migration-
public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('userId'); $table->string('name'); $table->string('username')->unique(); $table->string('gender'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->boolean('is_admin')->default(0); $table->rememberToken(); $table->timestamps(); }); }
create_feedback_table
Migration-
public function up() { Schema::create('feedback', function (Blueprint $table) { $table->increments('feedbackId'); $table->text('feedback'); $table->string('username'); $table->timestamps(); $table->foreign('username') ->references('username') ->on('users') ->onDelete('cascade'); }); }
FeedbackController
Get data,
class FeedbackController extends Controller { public function giveFeedback($username) { $userData = User::find($username); dd($userData->feedbacks); return view('feedback.givefeedback', compact('userData')); } }
users
Table-
feedback
Table-
This is the output on the blade, as you can see it outputs all the feedback, even though I only requested nerigupex
's feedback using routing.
If you need more code to solve this problem, please make a request and I will update the question accordingly. TIA.
Do this (only solves data loading issues)
1. Refactoring and migration
User migration
Feedback Migration
2. Refactor model
3. In feedback controller