I need to select multiple users and display the names as developers. But I get this error.
Exception
Property [name] does not exist on this collection instance. (View: D:\Laravel\BoomTech\bug-tracker\resources\views\project_issues.blade.php)
Code that should show the name/s of users:
{{ $issue->developer->name }}
Issues table:
public function up()
{
Schema::create('issues', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('project_id');
$table->foreignId('submitted_by_id');
$table->foreignId('developer_id');
$table->string('title', 255);
$table->string('comment', 255)->nullable();
$table->mediumText('description');
$table->text('status');
$table->text('type');
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
$table->timestamp('deleted_at')->nullable();
});
}
Issue User (pivot table):
Schema::create('issue_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('user_id');
$table->foreignId('issue_id')->nullable();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
Issue Model:
public function developer()
{
return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}
IssueCRUDController:
CRUD::addField([ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Developer",
'type' => 'select2_multiple',
'name' => 'developer', // the method that defines the relationship in your Model
// optional
'entity' => 'developer', // the method that defines the relationship in your Model
'model' => "App\Models\User", // foreign key model
'attribute' => 'name', // foreign key attribute that is shown to user
'pivot' => false, // on create&update, do you need to add/delete pivot table entries?
]);
This is many to many relationships so you need to do like this:
public function developers()
{
return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}
#foreach($issue->developers() as $developer)
{{ $developer->name }}
#endforeach
Related
I am using a customized subscription which is not laravel's default cashier.
and the migration looks as below
public function up()
{
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->bigInteger('plan_id')->unsigned();
$table->foreign('plan_id')->references('id')->on('subscription_plans');
$table->bigInteger('transaction_id')->unsigned();
$table->foreign('transaction_id')->references('id')->on('transactions');
$table->timestamp('subscribed_at');
$table->timestamp('expires_at')->nullable();
$table->boolean('is_active')->default(true);
$table->json('benefits');
$table->timestamps();
});
}
and the user relation as below
// subscription
public function subscriptions(): HasMany
{
return $this->hasMany(Subscription::class, 'user_id')->orderBy('subscribed_at', 'asc');
}
on a specific case, I update the is_active flag.
// in user model : User.php
public function createSubscription(Plan $plan): Subscription
{
$transaction = $this->createTransaction($plan);
$data = [
'plan_id' => $plan->id,
'transaction_id' => $transaction->id,
'is_active' => true,
'subscribed_at' => now(),
'expires_at' => now()->addDays($plan->validity),
'is_active' => true,
'benefits' => $plan->benefits
];
$this->subscriptions()->update(['is_active' => false]);
return $this->subscriptions()->create($data);
}
but it's updating all the subscribed_at timestamps.
Please help me to solve this.
Change the subscribed_at column type from timestamp to dateTime (Or make it nullable())
Like:
Schema::create('subscriptions', function (Blueprint $table) {
// ...
$table->dateTime('subscribed_at');
// ...
});
This is a continuation of my last question.
I like to create a relationship between a user (with an account type that’s equal to a “profile”) and my job posts. What I did was create a relationship like this in my models (not sure if correct tho)
User.php
public function jobposts()
{
$this->hasMany(JobPost::class)->where('account_type', 'profile');
}
JobPost.php
public function userprofile()
{
$this->belongsTo(User::class)->where('account_type', 'profile');
}
JobPostController.php
public function store(Request $request)
{
$this->validate($request, [
'job_name' => 'required|max:100',
'describe_work' => 'required|max:800',
'job_category' => 'required|not_in:0',
'city' => 'required|not_in:0',
'state' => 'required|not_in:0',
'zip' => 'required|regex:/\b\d{5}\b/',
]);
dd(auth()->user()->jobpost()->job_name);
}
2021_11_20_211922_create_job_posts_table.php
Schema::create('job_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->contrained()->onDelete('cascade');
$table->string('job_name');
$table->text('describe_work');
$table->string('job_category');
$table->timestamps();
});
Got 2 questions about what I can do in the JobPostController.php.
How do I dd() to test the output?
This seems wrong
dd(auth()->user()->jobpost()->job_name);
How do I add it correctly into the DB like this?
public function store(Request $request)
{
$request->user()
->jobpost()
->create([
'job_name' => $request->job_name
]);
}
Hi i'm trying to seed my database with fake data.
For that i've 2 models User and Patient.
in User.php
public function patients()
{
return $this->hasMany(Patient::class);
}
in Patient.php
public function user()
{
return $this->belongsTo(User::class);
}
My DatabaseSeeder.php
$users = factory(User::class, 10)->create();
$users->each(function ($user) {
$user
->patients()
->saveMany(factory(Patient::class, 10)
->create());
});
When i'm trying to seed with relationship I got the error
general error: 1364 Field 'user_id' doesn't have a default value
isn't the relationship supposed to fill the foreign key ?
// Edit more information
Patient Migration
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->date('birth_date');
$table->nullableTimestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users');
});
PAtientFactory
$factory->define(Patient::class, function (Faker $faker) {
return [
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'birth_date' => $faker->date,
];
});
user Migration
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->string('email', 191)->unique();
$table->string('password', 191);
$table->rememberToken();
$table->string('lang')->default('en');
$table->tinyInteger('change_password')->default('1');
$table->softDeletes();
$table->nullableTimestamps();
});
UserFactory
$factory->define(App\Models\User::class, function (Faker $faker) {
return [
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
'lang' => $faker->randomElement(['fr', 'en']),
'change_password' => 0,
];
});
Try following, it's working in my project. You can not use relationship to create multiple records the way you are doing. Following will achieve the same.
factory(User::class, 10)->create()->each(function($u) {
factory(Patient::class, 10)->create(['user_id' => $u->id]);
});
I'm studying some Laravel and at some point I had to re-migrate the database because I had to change a table. I'm using postman to do testing, and one of the api methods give me the error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: events.user_id (SQL: insert into "events" ("sport", "title", "players", "when", "description", "location", "updated_at", "created_at") values (Hockey, Grass Hockey, 12, 30/09/2018, Come join us, Fairview park, 2018-11-08 22:19:45, 2018-11-08 22:19:45))
so it seems to be a problem with the events.user_id which I changed on a table called Events to have a relationship with the Users table. Some examples I found by researching is on table fields that were not ids, so I don't how to figure this one out, maybe some of you can help me!
here are the migrations for Events and Users:
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->string('sport');
$table->string('title');
$table->decimal('players', 8, 2);
$table->date('when');
$table->mediumText('description');
$table->string('location');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Here are the models:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location'
];
public function user()
{
return $this->belongsTo('App\User');
}
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function events()
{
return $this->hasMany('App\Event');
}
}
And below is the api method that is giving me the error:
Route::post('/admin/create-event', function (Request $request) {
$data = $request->all();
$event = Event::create(
[
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
Thanks guys!
Edit:
Route::middleware('auth:api')->post('/admin/create-event', function (Request $request) {
$user = $request->user();
$data = $request->all();
$event = Event::create(
[
'user_id' => \Auth::user()->id,
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
I think you have to add 'user_id' to $fillable of Event class:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
You need to pass the user_id:
'user_id' => \Auth::user()->id
The example above requires an authenticated user in the session, but if you are making the request using postman you probably don’t have one.
Anyway, you need to provide the user_id that will be stored in the database.
EDIT
Eloquent's method create will copy to the model only the attributes defined as fillable. So you have two options:
Add user_id to $fillable
Use newInstance instead of create, manually set the user_id with $event->user_id = ..., and manually save the $event model with $event->save();
So I have a user table, a role table and an intermediate table for those 2, user_role. It's a many-to-many relationship between the first 2 tables.
I want to return the count of the users which have a specific role but I can't seem to get it right.
My migrations:
user:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
});
role:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
user_role:
Schema::create('user_role', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->integer('role_id');
});
Relationship between them:
public function users(){ //in role model
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id')->withTimestamps();
}
public function roles(){ //in user model
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id')->withTimestamps();
}
Role Seeder:
public function run()
{
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
}
in controller:
public function adminDashboard(){
$users = User::all();
return view('admin.dashboard')->withUsers($users);
}
in view:
{{ $users->count() }}
This obviously, returns the total count of users in user table. Any ideas on how to return the count of users which have a specific role?
use $role->users()->count()
To iterate over the roles and display the count of users, you can use this:
public function adminDashboard(){
$roles = App\Role::all();
return view('admin.dashboard', compact('roles'));
}
In your dashboard view:
#foreach ($roles as $role)
<p>Role {{ $role->name }} has {{ $role->users()->count() }} users</p>
#endforeach