eloquent - Laravel 5.3 belongsTo relation on same table shows no result

I'd like to make a relationship on the same table but I'm not sure it's possible...I have a table jobs with the fields id, name and parent_id. I want to get some jobs and their parent (and their own parent if they have one, etc.).Here's my model :class Job extends Model{ public function jobParent() { return $this->belongsTo('App\Job', 'parent_id'); }}In my controller I do that :$select = Job::take(10) ->with('jobParent') ->get();I displayed the queries and I can see the one for the relationsh...Read more

eloquent - Laravel 5 hasManyThrough Pivot Table

I am trying to create a relationship to access a table called comments through a model called grade, loaded through the students in the gradeBoth the Grade and Student models belongToMany of the otherFrom my understanding, it is not possible to access a hasManyThrough relationship that requires a pivot table (comments do not have a Grade identifier, only a student identifier)class Grade extends Model{ public function comments(){ return $this->hasManyThrough("App\Comment","App\Student"); }}I have these functions I found for Larav...Read more

eloquent - Laravel 5.2 query scopes unexpected behavior with orWhere

I use a query scope that should append a orWhere condition but it appends a normal where (with AND). If I remove the query scope and put it directly it does return the OR condition. The query looks like this:$query = MyModel::firstQueryScope()->secondQueryScope();FirstQueryScope:public function scopeFirstQueryScope($query){ return $query->where('someAttribute', 0);}Second Query Scope:public function scopeSecondQueryScope($query){ return $query->orWhere('someOtherAttribute', 0);}Building the query this way should be the same as:$q...Read more

eloquent - Laravel nestedwhere Parse error: syntax error, unexpected '}'

Symfony\Component\Debug\Exception\FatalThrowableError: Parse error: syntax error, unexpected '}'I followed this resources for nested where here: How to combine WHERE clauses in Eloquent but get the following error while running the codes. The line where it broke was the curly bracket of the callback function, what's wrong here?$providers = DB::table('users')->where('verified', '=', 1)->where('status', '=', 1)->where(function ($query) use ($search) { $query->where(DB::raw('lower(name)'), 'LIKE', "%".strtolower($search)."%") -&g...Read more

how do I use data from the database within my controller in laravel using eloquent

I am trying to fetch the first name, second name and course from the database. My model is called Youth. $id = auth()->user()->id; $firstname = Youth::where('id', $id)->get(['firstname']); $secondname = Youth::where('id', $id)->get(['secondname']); $course = Youth::where('id', $id)->get(['course']);Then use the fetched data in my string called notification which is to be stored in my notification table. $notification = 'Internship application by ' . $firstname . $secondname . ' from ' . $start_date . ' to ' . ...Read more

Eloquent - How to use "Has Many Through" relation?

I have three tables - products, features and product_feature - asproducts - id - namefeatures - id - keyproduct_feature - product_id - feature_id - valueI was retrieve all (key, value) pairs for a product. The SQL statement isSELECT key, value FROM productsJOIN product_feature pfON pf.product_id = "Product ID"JOIN features fON f.id = pf.feature_idHow do I established that relationship// Inside Product modelfunction features() { // Has many through relationship}...Read more

laravel 5.1 - Auto-generate and auto-update timestamps in Eloquent

I am new to Laravel and I am working on my database migrations. For one table, I've included the $table->timestamps() shortcut in my table definition. To my dismay, I found that after I seeded the table, the values were 0000-00-00 00:00:00 for both created_at and updated_at.I was thinking to change the column definitions to have DEFAULT CURRENT_TIMESTAMP and DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, but then I wondered why Eloquent wasn't already doing this. I figured it must be For a Good Reason(tm). I suppose it's for compatib...Read more

eloquent - How to add the same event listener for all my models?

Suppose I have the models A, B, C and D. Now I want to listen for their created event. Usually, I'd go to my AppServiceProvider and add the events for each model, like this:public function boot(){ A::created(function ($a) { //some code }); B::created(function ($b) { //some code }); C::created(function ($c) { //some code }); D::created(function ($d) { //some code });}The code is the same, and I'd like to make that process faster since I actually have 70++ models. So is there a way to bind a sin...Read more

Laravel Eloquent Many-To-Many Query Producing Extra null WHERE clause

I'm using Eloquent to produce results from a query comprised of three tables:photos (id)photos_to_photosets (photo_id, photoset_id)photosets (id)My models have their many-to-many relationships defined as:class Photo extends Model{ public function photosets() { return $this->hasMany(PhotoSet::class, 'photos_to_photo_sets'); }}Andclass PhotoSets extends Model{ public function photos() { return $this->belongsToMany(Photo::class, 'photos_to_photo_sets'); }}Now, to fetch results I'm forced...Read more

Eloquent Relationship Laravel 5.4

I have three tables as follows users, jobs and job_statuses with the following simple schema.**Users Table** id, user_id, email, password**Jobs Table** id, user_id, title, description, status_id**Job_statuses Table**id, statusI have successfully retrieved a list of Jobs posted by an authorized user using a one-to-many relationship but I can't get hold on the status using the status_idUser Modelpublic function job(){ return $this->hasMany(Job::class, 'user_id')->take(5);}Job Model public function user() { return $this->belongsTo(U...Read more

Eloquent: check extra pivot column

Inside my User model I would like to make a isMember function. public function isMember(){ return(\Auth::check() && "get the status value here" == 1)}I got two models. User, Club. Their pivot table: club_useruser_idclub_idstatusThe 'status' column holds 0 or 1. Now, how do i check the value for the extra column 'status'? Update: It's a many-to-many relationship....Read more

eloquent - How to query the pivot table

I need to query the pivot table project_user to get the column where done = 1, and where the project id that exist in project_user. ? How to use this in Eloquent ? .Thank you in advance.projects -id -user_idusers -idproject_users -user_id -project_id -doneclass Projec extends Model{ public function users(){ return $this->belongsToMany(User::class)->withPivot('done'); }} class User extends Model{ public function projects(){ return $this->belongsToMany(Project::class)->withPivot('done'); ...Read more

eloquent - Laravel Relationship: Fetch child and its Parent from same table

I have been using Laravel 5.4 for few weeks now. Trying my hands on the Laravel Relationships. I'm trying to fetch a record and get the relation category record. I also want to get the parent of the fetched category using the same relation.Category Table:--------------------------------------------| id | name | parent_id ||------------------------------------------|| 1 | Deals | 0 ||------------------------------------------|| 2 | Dining | 1 |-------------------------------...Read more

eloquent - How to use laravel accessor in trait?

I would like to put accessor in trait, and for some reason this is not working (i have current applocale in session):Trait:namespace App\Traits;trait TranslateEntities{ public function getNameAttribute($value) { if (session('applocale')=='en') { return $value; } else { return trans("entities.".$this->code); } }}Model:namespace App\Models;use App\Traits\TranslateEntities;class Repairstatus extends \Eloquent { use TranslateEntities; (...)}This way i'm not getting translated entity, ...Read more

eloquent - Route model binding in Laravel 5.6

I am using Laravel resource controller with route model binding in my API development project. I have below codepublic function show(Post $post){ return $post->comments()->get();}I am using below URLhttp://127.0.0.1:8000/api/posts/1I would like to retrieve both post values with comments value.But I am getting only comments values....Read more