I want to populate the whole Edit form, but Select Box does not grab the value.
First time working with an eloquent relationship. I'm trying to access the Category method yet I get this error:
Property [categoryId] does not exist on this collection instance.
And I installed composer require laravelcollective/html package.
{!! Form::select('categoryId',
\Modules\Category\Entities\Category::pluck('title', 'id')->toArray(),
old('categoryId', $faq->categories->categoryId) , [
'class' => 'form-control',
'id' => 'categoryId',
]) !!}
Category.php
class Category extends Model
{
protected $guarded = [];
}
Faq.php
class Faq extends Model
{
protected $fillable = ['subject', 'body', 'userId'];
public function scopeSearch($query, $term)
{
return $query->when($term, function ($query, $term) {
return $query->where('subject', 'like', "%{$term}%");
});
}
public function user()
{
return $this->belongsTo(User::class, 'userId');
}
public function categories()
{
return $this->belongsToMany(Category::class, 'faq_category', 'faqId', 'categoryId');
}
}
Related
What Eloquent model would you use to:
Get all Pages that its Company brand color is red/slug.
Where brand color is a pivot table and stored as an ID on the Company table.
So you have brand_colors id, name, slug, hex
Have company where it has brand_color_id
And Pages that has just the company ID.
I want to grab all pages whose company brand color is X.
How would you go about it?
This table has the company_id
class WebsitePage extends Model
{
use HasFactory;
public function scopeFilter($query, array $filters) {
// Get all pages with a color that the company has
$query->when($filters['color'] ?? false, fn($query, $color) =>
$query->whereHas('color', fn ($query) =>
$query->where('name', $color)
)
);
}
// Where URL slug 'red' color, associated with company brand_color_id matches brandColor slug
// or just simpley call $company->color() ?
public function color()
{
// return $this->with(Company::class, 'brand_color_id');
// return $this->belongsTo(Company::class, 'company_id');
// dd($this->with())
// return Company::with('color.red');
}
This table has brand_color_id, etc.
class Company extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'slug',
'description'
];
public function pages() {
return $this->hasMany(WebsitePage::class);
}
public function color() {
return $this->belongsTo(BrandColor::class, 'brand_color_id');
}
}
This table has: id | name | slug | hex
class BrandColor extends Model
{
use HasFactory;
}
So knowing this, how would you get all pages whose company color is the one filtered?
In terms of the page controller, this is what I'm doing:
class PageController extends Controller
{
public function index(WebsitePage $websitePage)
{
// return view('web.inspiration.pages.index', [
// 'pages' => WebsitePage::latest()->paginate(30)
// ]);
return view('web.inspiration.pages.index', [
'pages' => WebsitePage::latest()->filter(
request(['color'])
)->paginate(30)->withQueryString()
]);
}
}
Your model layout isn't described that well, but I think you just want to define a HasOneThrough relationship to join WebsitePage to BrandColor:
class WebsitePage extends Model
{
public function company(): BelongsTo
{
return $this->belongsTo(Company::class);
}
public function color(): HasOneThrough
{
return $this->hasOneThrough(BrandColor::class, Company::class);
}
}
class Company extends Model
{
public function color(): BelongsTo
{
return $this->belongsTo(BrandColor::class);
}
}
class BrandColor extends Model
{
public function company(): HasOne
{
return $this->hasOne(Company::class);
}
}
Then in your controller, just use a condition on your whereHas() and with() calls:
class PageController extends Controller
{
public function index(): View
{
$color = request("color");
$pages = WebsitePage
::whereHas("color", fn ($q) => $q->where("color", $color))
->with(["color" => fn ($q) => $q->where("color", $color)])
->paginate(30)
->withQueryString();
return view("web.inspiration.pages.index", compact($pages));
I am have some issue with eloquent relationship my first time working with it, after selecting and displaying list of selected events, I want to also select the ticket_id base on the event_id common between both(events and events_ticket) table, thanks for the help
Error Showing ->
Trying to get property 'ticket_id' of non-object (View: C:\wamp64\www\mahive\resources\views\tickets\index.blade.php)
Both Model
class EventsTicket extends Model
{
public $table = "events_ticket";
use HasFactory;
protected $fillable = [
'event_id',
'ticket_id',
'ticket_name',
'ticket_amount',
'ticket_sold',
];
public function event() {
return $this->belongsTo('App\Models\Event');
}
}
class Event extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'event_id',
'event_name',
'event_category',
'event_type',
'event_mode',
'event_description',
'event_image'
];
public function userModel() {
return $this->belongsTo('App\Models\User');
}
public function eticket() {
return $this->hasMany('App\Models\EventsTicket');
}
}
Controller
public function index()
{
$events = Event::where('ticket_statue', 'active')->with('eticket')->get();
return view('tickets.index', ['event_data' => $events]);
}
View
#foreach($event_data as $event)
{{ ucwords($event->event_name) }}
{{ $event->eticket->ticket_id }}
#endforeach
In this code every Event has many eticket. Try this:
#foreach($event_data as $event)
{{ ucwords($event->event_name) }}
{{ optional($event->eticket->first())->ticket_id }}
#endforeach
Use optional because there may not be any etickets.
So I have this model, say City. And it has a OneToMany relationship with another model, say, Citizen.
On the city model, I have defined a relationship helper function
public function citizens()
{
return $this->hasMany(Citizen::class, 'city_id', 'id');
}
Now my problem is that, in a command, I have :
$cities = City::with('citizens')->get();
foreach ($cities as $city) {
$citizens = $city->citizens->pluck('user');
}
Yet it doesn't return anything. To get values I must turn this line to
$cities = City::all();
foreach ($cities as $city) {
$citizens = $city->citizens()->get()->pluck('user');
}
Does anyone have a clue how this might happen ? This started happening today with no apparent reason.
EDIT
To further illustrate the situation,
$cities = City::with('citizens')->get();
foreach ($cities as $city) {
dd($city->citizens()->count()); // => 5
dd($city->citizens->count()); // => 0
}
Here are the models definitions
// City.php
class City extends Model
{
use Searchable;
protected $table = 'cities';
public $incrementing = false;
protected $perPage = 20;
protected $fillable = [
'name',
'unique_code',
'extra_attributes'
];
protected $casts = [
'id' => 'string',
'codes' => 'array',
'extra_attributes' => SchemalessAttributes::class,
];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = $model->id ?: Str::orderedUuid();
});
}
public function toSearchableArray(): array
{
return [
'name' => $this->name,
];
}
public function citizens()
{
return $this->hasMany(Citizen::class, 'city_id', 'id');
}
}
// Citizen.php
class Citizen extends Model
{
public $incrementing = false;
protected $perPage = 20;
protected $table = "citizens";
protected $fillable = [
'user_id',
'level_id',
'city_id',
];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = $model->id ?: Str::orderedUuid();
});
}
public function user() {
return $this->hasOne(User::class, 'id', 'user_id')->withTrashed();
}
public function city() {
return $this->hasOne(City::class, 'id', 'city_id');
}
}
the relation between City and Citizen is City hasMany Citizens...
In Laravel, hasMany relation reverse is belongsTo Not hasOne, see Laravel doc
so you should correct the relation In Citizen Model like this:
public function city() {
return $this->belongsTo(City::class, 'city_id');
}
There are two issues, one of which OMR has highlighted (you've used an incorrect relationship in your Citizen class), but that isn't the main issue. You're trying to pluck another relationship but unless you explicitly tell it to, Laravel won't eager load that relationship. You've only told it to eager load the Citizen relationship, not the User relationship. Thankfully, Laravel does support nested relationships. You need to update your query thusly:
$cities = City::with('citizens.user')->get();
The best way to solve this issue is by eager loading the citizens when you're getting your cities, that way you wont be executing too many queries (as you will have to get citizens for each city individually), it will save you a lot of execution time in the future when the database gets bigger if you do this :
$cities = City::with('citizens')->get();
foreach($cities as $city) {
$items = $city->citizens->pluck('...');
}
Hey there stackoverflow
I am currently building a course application as part of my laravel project.
My problem lies in how the eloquent handle model relations, i'm still kinda new to eloquent, so hopefully you can answer my question.
The structure
The Course has many episodes and each episode has many sections.
Which means I have 3 tables in the DB. Courses -> course_episodes -> course_episode_sections
ID table is where i connect courses with users - course_users.
Right now i can create courses and and put in all the data correctly.
The Problem
I need to retrieve all the courses and its nested children that the user has bought, which is connected in the course_users table with columns course_id and user_id
Course structure
Same stucture in DB
course: {
name: null,
sub_title: null,
estimate: null,
trailer: null,
type: null,
text: null,
course_episodes: [
{
name: null,
section: [
{
order: null,
type: null,
content: null,
},
]
},
]
}
Model Pictures
My models as of right now.
class CourseUsers extends Model {
protected $fillable = [
'id',
'course_id',
'user_id',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courses()
{
return $this->belongsToMany(Course::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function scopeFindForUserId($query, $userId)
{
return $query->where(function ($q) use ($userId) {
$q->where(function ($q) use ($userId) {
$q->where('user_id', $userId);
});
});
}
Course model
class Course extends Model{
protected $fillable = [
'id',
'name',
'sub_title',
'type',
'estimate',
'trailer',
'gateway_id',
'text',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->hasMany(CourseEpisode::class);
}
public function courseUsers() {
return $this->hasMany(CourseUsers::class);
}
public function scopeActive(Builder $builder)
{
return $builder->where('active', true);
}
Course episode Model
class CourseEpisode extends Model implements HasMedia {
use HasMediaTrait;
protected $fillable = [
'id',
'course_id',
'order',
'name',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function course()
{
return $this->belongsTo(Course::class);
}
public function courseSection()
{
return $this->hasMany(CourseEpisodeSection::class);
}
Course episode sections
class CourseEpisodeSection extends Model {
protected $fillable = [
'id',
'course_episode_id',
'order',
'type',
'content'
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->belongsTo(CourseEpisode::class);
}
According to your explanation, course_users table holds many-to-many relationship between Course and User model. In case of a many-to-many relationship, you actually don't need a CourseUser model. This kind of table which holds many-to-many relationship is called pivot table. Read more from the Official Documentation
I am defining only the relationships with your Course, User, CourseEpisode, CourseEpisodeSection models.
Course.php
class Course extends Model
{
public function courseEpisodes()
{
return $this->hasMany(CourseEpisode::class);
}
public function users()
{
return $this->belongsToMany(User::class,'course_users')->withPivot('active');
}
}
CourseEpisode.php
class CourseEpisode extends Model
{
public function courseSections()
{
return $this->hasMany(CourseSection::class);
}
}
User.php
class User
{
public function courses()
{
return $this->belongsToMany(Course::class,'course_users')->withPivot('active');
}
}
If you want to get all the children relationships from a user, use nested eager loading :
$user_with_nested_course_data = User::with('courses.courseEpisodes.courseSections')->find($id);
I'm studying event message board. I can display table data by every Users own post. however I would like to display All post too. I wrote this as $tasksall but it didn't work. Could someone teach me what is wrong?
AController.php
public function index()
{
$tasks = Auth::user()
->tasks()
->orderBy('is_complete')
->orderByDesc('created_at')
->paginate(5);
$tasksall =
->tasks()
->orderBy('is_complete')
->orderByDesc('created_at')
->paginate(5);
return view('tasks', [
'tasks' => $tasks, 'tasksall' => $tasksall
]);
}
Task.php (model)
class Task extends Model
{
protected $casts = [
'is_complete' => 'boolean',
];
protected $fillable = [
'title',
'is_complete',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
AController.php I add this code
public function person()
{
return $this->belongsTo('App\Models\Task');
}
public function getData()
{
return $this->id . ':'/ $this->person->name.')';
}
index.blade.php I add this code
{{ $task2->getData() }}
You can just write a query to get all the task using eloquent to get all the tasks.
$tasksall = Task::all();
Have a look at this link.
Also for you case I think the problem is you are getting task from the User model so you $task will contain only task related to that particular user as you have a belongsTo relation of task with user.
For Your case to get name of User from task.
//Task model
class Task {
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
Then you can query like this in your controller.
$task = Task::find($id);
$name = $task->user->name;