PavanKataria

PavanKataria

Member Since 4 Years Ago

London

Experience Points 13,255
Experience Level 3

1,745 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 88
Lessons
Completed
Best Reply Awards 10
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

19 Oct
2 years ago

PavanKataria started a new conversation Passing Related Attribute To Create Method - Model Factories

$factory->define(CourseOffer::class, function (Generator $faker) {
    return [
        'course_unit_id' => factory(CourseUnit::class)->create()->id,
        'quota_id' => factory(Quota::class)->create()->id,
        'regulation_id' => Regulation::findOrCreateWithRegulationStartYear(2016)->id,
        'fee' => 4000,
    ];
});

$factory->define(CourseUnit::class, function (Generator $faker) {
        $duration = $faker->numberBetween(3, 4);
    return [
        'code' => $faker->sentence,
        'degree' => $faker->words(1, true),
        'course' => $faker->words(4, true),
        'length' => $duration . ' years',
        'duration' => $duration,
    ];
});

Given the following two factory methods, I’d like to be able to do this: `$courseOfferOne = factory(CourseOffer::class)->create(['course' => 'a'] But the `cour column doesn't reside in `CourseOff, it actually lives in the `CourseUn model. What can I do to make it as easy as passing in a course attribute to my `CourseOff model without changing the schema?

06 Oct
2 years ago

PavanKataria left a reply on Homestead Not Mapping Properly

@mehany so when I run your global status command I get the following output:

id       name   provider state  directory                           
--------------------------------------------------------------------
There are no active Vagrant environments on this computer! Or,
you haven't destroyed and recreated Vagrant environments that were
started with an older version of Vagrant.

What have I done wrong during the vagrant homestead box upgrade? It seems like homestead is ignoring my .yaml folder mapping instructions after the update.

01 Oct
2 years ago

PavanKataria left a reply on How Do You Filter Children Models?

I think I've done it:

Route::get('/', function () {
    return dump(Branch::
        with(['studentEnrolments' => function($q){
            $q->whereHas('student.person', function($query) {
                $query->where('gender', 1);
            });
        }])
        ->get()->toArray());

PavanKataria started a new conversation How To Filter Children Models

Here are the relationship definitions

  1. A Branch hasMany StudentEnrolment
  2. StudentEnrolment belongs to ONE Student
  3. Student belongs to ONE Person
  4. The 'gender' column is of type boolean and lives in the Person model. Where the value 0 is for male, and the value 1 is for female.

How does one filter the Branch's student enrolments array based on the gender of the person?

This doesn't seem to work:

Branch::with(['studentEnrolments.student.person' => function($q){
            $q->where('gender', 1);
        }])
        ->get()->toArray());

What do I need to do to get this working? It still returns the full set of Branch's student enrolments array.

PavanKataria started a new conversation GROUP BY On Eager Loaded Table.

GENDER | total_students 0 | 9 1 | 14

p.s. that would make a total students = 23. 9 male students, and 14 female students.

To simplify the question, I'm trying to produce the above result set with as much eloquent as possible. Here's what the required SQL query looks like to produce the above result:

SELECT persons.gender, COUNT(*) as 'total_students' FROM student_enrolments as se

LEFT JOIN students on se.student_id = students.id
LEFT JOIN persons on students.person_id= persons.id

GROUP BY persons.gender

Here’s what I’ve tried so far to recreate this in eloquent:

StudentEnrolment::with([
        'student.person' => function($q){
            $q->groupBy('gender');
        }
    ])
        ->selectRaw('count(*) as total_students')
        ->get()
        ->toArray()

Notice the inner Group by to reach the gender attribute on the person table that belongs to the student model. But that produces the following incorrect query: string 'select count(*) as total_students from `student_enrolments`' (length=59) And when var dumping the toArray result… I get the following:

      'total_students' => int 23 //<-notice how GROUP BY had no affect in splitting the result
      ...

I also tried doing a group by as a chain but by trying to reference the column with dot syntax like so: ->groupBy(‘student.person.gender’)at didn't work too.

What can I do to get this working?

04 Apr
3 years ago

PavanKataria left a reply on Laravel Forge Let's Encrypt SSL 502 Bad Gateway.

Any updates on this as I'm getting the same error..

03 Oct
3 years ago

PavanKataria left a reply on Can I Do This In One? If Not Whats The Most Efficient Way?

I don't understand your question. But this is elegant :) GroupRoutePermission::all();

30 Sep
3 years ago

PavanKataria left a reply on Users And Customers, Where Some Users Are Customers

@myflashstore Since a user will always be a customer, but a customer may or may not be an existing user, then just store the customer_id on the user's table, and have a customers table with a hasOne relationship to User. You don't want a bunch of null values in your customers table if you were to store the user_id there, since not every customer will be a user.

Having one foreign key to tie the relationship between the two tables is more than enough. I've stated my reason above where I would place the foreign key relationship.

PavanKataria left a reply on Eager Loading All Relationships

@prymribb Hey, well I wondered the same thing since every single query I was making on my Orders model went hand in hand with a with->(OrderLines::class) at the beginning. So it made sense to want to have something which automatically eager loaded my OrderLines dataset. Another use case in my app, I have another model called Agent which also requires the eager loading of three other models related to it for everything to make sense in the iOS client.

I did some research last week and Taylor Otwell had documented in his Model class a variable which allowed one to set their eager loaded relationships in their own model to automatically enable the loading of relationships without having to specify the with method.

Here's the documentation on that: Model.php

/**
     * The relations to eager load on every query.
     *
     * @var array
     */
    protected $with = [];

All Eloquent models inherit from this class you'll notice the line: class YourModelName extends Model this means you can use the with variable yourself by specifying an array. Here's an example:

    // order
    protected $with = array('orderlines');
    // agent
    protected $with = array('state', 'direction', 'areas');

It's important to remember to only eager load relationships that have to be loaded each and every time, otherwise you will be wasting time on queries especially if you're not going to use them.

In my case it's required. That's how you achieve automatic eager loading.

I hope this will help you and future members visiting this post. If it helped don't forget to mark the answer.

Pavan

23 Sep
3 years ago

PavanKataria left a reply on Appending Relation Sum

@JarekTkaczyk ah, I didn't know this :|

I've noticed in one of your posts on your website where you use getRelation quite a bit. I've seen it used for some solutions to. I feel like I'm missing out. Where can I learn about this in depth?

PavanKataria left a reply on API Authentication For Mobile Applications

That's a big question. I currently haven't learned about authentication yet with server development but will do soon in the next few months. I've just been learning about API development, and RESTful webservices theory.

Hopefully someone will be able to help you out :) . It might also be helpful to narrow the questions down.

Good luck,

Pavan.

22 Sep
3 years ago

PavanKataria left a reply on Eloquent Relationships Returning Empty

@TobyMellor can you explain why my answer wasn't the chosen one? I explained the details to your question and how to fix them, rather than a copy and paste solution. You might want to rethink the marked answer :)

21 Sep
3 years ago

PavanKataria left a reply on Autoplay Series Videos

I agree +1 to this.

PavanKataria left a reply on Appending Relation Sum

It looks like your motion_id is inside a motionRank relationship definition. Instead try this:

public function motionRank()
    {
      return $this->hasOne('App\Vote')
        ->selectRaw('sum(position) as rank')
        ->groupBy('motion_id');
    }```

You should have the result look like this:

"motionRank": 7


Tag me and let me know if that helps.

PavanKataria left a reply on Parameters In Relations Are Mixed

@pckz Do you really need all those relationship definitions? What do the models do? how are products, users, and messages related in reality? lol they seem like very different things.

However, I can understand a relationship between a product and a user through message so that a user can write a message about a certain product, but it would be great if you could explain the reality of these relationships. What are you trying to do in your view?

PavanKataria left a reply on Overthinking In Which Class To Put A Method In.

@belisar where can I read up on JSON api for fractal? and what it's advantages are? I'm using eloquent collections with nested relationships, as well as outputting to json

20 Sep
3 years ago

PavanKataria left a reply on Eloquent Relationships Returning Empty

@TobyMellor Hey Toby, since the foreign key sits in the Album model referencing to an Artist model, and you have mentioned that each album can only have one artist, then in your Album model the relationship method needs to be defined as a belongsTo. relationship. You then mentioned that an artist can have many albums, this therefor means that the relationship needs to be defined as hasMany. This would yield your models looking like this:

Album

public function artist()
{
        return $this->belongsTo(App\Artist::class);
}

Artist

public function albums()
{
        return $this->hasMany(App\Album::class);
}

Now when you will be able to run these commands:

>>> $album->artist()->get() and >>> $artist->albums()->get()

Ensure that you also have data in your tables.

PavanKataria left a reply on SelectRaw Not Working

@dharmendrajadon SQLSTATE42000 means that you have a syntax error somewhere. I can't see anything that stands out, but I would suggest commenting out the bottom queries, and running them one by one, uncommenting each line after each successful sql execution so that can see which query actually contains the syntax error.

Can you show me the full error?

PavanKataria left a reply on Overthinking In Which Class To Put A Method In.

@bugsysha sorry. I have updated my post to add in the URL link that Iw as meant to insert before. Please take a look

PavanKataria left a reply on Nested Method Eager Loading

@JarekTkaczyk Could have liked it ;) Anyway, jokes aside, I'm not sure what happened, no sleep has caused me to have a brain freeze! Momentarily stuck in a while loop! I answered his initial generic question but didn't deal with his problem! lol.

Well I'm glad you did anyway. :)

PavanKataria left a reply on Overthinking In Which Class To Put A Method In.

@bugsysha Traits are good for when you have duplication across classes. Here we have a situation where it's only in one class... hmmm I can however imagine this code being duplicated for my FactoriesController, UsersController, AccountsController, and so on so forth...

Hmmm, what would I call this trait then? and what would the method look like for it to work across my controllers? And what of the fractal manager instance, would I still need to instantiate that in every controller or... will that be instantiated inside the trait? And what of the transformers that get instantiated into the fractal manager?

PavanKataria started a new conversation Overthinking In Which Class To Put A Method In.

Hey, here's some code that I have in my controller which contain methods all connected to my routes.

Each method calls a method from my repository, and then calls a method on a transformer manager class to process the dataset into the final result. (appending the wrapper data around my json, essentially)

I have an OrdersController, which has a Fractal manager, orderRepository and OrderService class all of them instantiated through the constructor.

OrderRepository, contains all my database querying logic

OrderService I was thinking of putting my duplication method here.. there's nothing in here atm. If I move the duplication into a method in this class then that'll mean I'll have to pass a fractal instance to this method too which is ugly, and I could instead instantiate my fractal manager here instead of inside my controller...

Normally the controller is responsible for handling HTTP related stuff, json, and transformations, right? So should I just decouple the duplication in my OrdersController instead?

Any thoughts? Lol. Sorry, normally this kind of stuff doesn't hinder me at all, not sure what's happening today.

PavanKataria left a reply on Eloquent Get Latest Tickets -> HowTo?

@uibar why don't you set up a hasManyThrough relationship on your User model?

http://laravel.com/docs/5.1/eloquent-relationships#has-many-through This way you can access all tickets which are referenced to the user's locations.

> Users->locations->tickets

It allows you to create and reach long distant relations with a shortcut relationship.

PavanKataria left a reply on Nested Method Eager Loading

@slaughter550 Great question. Allow me to answer it:

Why does this work

$this->load('question', 'question.assessment'); 

while this does not work.

$this->load('question', 'assessment');

This is because when you query on your model, you have to eager load relative to that model. There is no relationship defined between assessment and your model which is why you're not able to lazily eager load them. Now when you do question , that works because there is indeed a relationship defined called question on your model class. You can also eager load nested relationships using dot notation. Because question.assessment works you can be sure that there is an assessment relationship defined belong to the question model.

So you're technically eager loading the grandchildren belonging to the question model which belongs to the parent model which you referred to as model.

Just so you know, you don't have to eager load, questions seperately if you're already eager loading question.assessment, since you can't eager load the grandchild assessment without eager loading it's parent called: question.

I hope that answers your question, if it does, please do mark the answer. Thanks

Pavan

PavanKataria left a reply on Different Models Based On Table Column, All Extending A Base Model

@dprevite this is exactly what polymorphism does for you.

You have a table called media_collections, and a table for videos, and a table for photos; you can have any other media tables connected to it to.

Each media type table of course has their own rows, for example the videos table may have column names such as duration, genre, movie_budget and so on. These are attributes that you won't find in your Photos table since you might instead have pixels, pixel_width, pixel_height, resolution and so on. Yet both these can fall inside the collections table.

So in your collections table you would have at least two fields called, imagable_id, and imagable_type. This would look like the following:

    id - integer
    duration - timestamp
    genre_id - reference id

photos
    id - integer
    resolution - integer
    pixel_width - integer
    pixel_height - integer

media_collections
    id - integer
    imageable_id - integer
    imageable_type - string```

This will then store the appropriate model's id number, and model's type, so that when you process the rows on your `media_collections` table, they will automatically convert it to the correct model type.
You would retrieve a row on your polymoprhic table like so:

$mediaCollection = App\MediaCollection::find(1); $imageable = $mediaCollection->imageable;


So here the imageable relation on the `MediaCollection` model will return either a `Movie` or `Photo` instance, depending on which type of model owns the `MediaCollection` instance.

I hope this helps. 
If it does then please do mark the answer. 

Thank you

Pavan.
18 Sep
3 years ago

PavanKataria left a reply on Nested Relation Query

@david-w Yes, set up a hasManyThrough relationship on your User model so you can access all projects through the user's associated customers.

http://laravel.com/docs/5.1/eloquent-relationships#has-many-through This way you'll be able to retrieve just a collection of Projects.

If you do it your way then as you have noticed you will get nested relationships because of eager loading, you could filter those out, but the nested relationship will still be there, and then you'd have to use a Collection method to extract the projects in post, which you don't want to do.

I hope that helps. Don't forget to mark the answer if it helped!

Pavan

PavanKataria left a reply on Ordering Table

Ok @Ghaleon I thought it might have been that. As I said, you might have written your code in the wrong part of the class or not inside a method at all!

If it helped, please do mark the answer :)
Thanks

Pavan

PavanKataria left a reply on Most Used Tags In Many-to-Many Relation

@ftiersch

Well, you could do it with eloquent but this requires post-processing which isn't clean in my opinion especially as you won't be filtering on the SQL domain which is ideal to do it in as you don't want to load data just so you can do some math with it after.

PavanKataria left a reply on Ordering Table

Can you show me the full source code please

paste the code into something like http://laravel.io/bin

The chances are you are not writing this database query statement inside a method. Once you have that fixed then don't forget to add two colons after DB like so:

$professor = DB::table('professors')->orderBy('name','asc')->get();
17 Sep
3 years ago

PavanKataria left a reply on Polymorphic Relations And Scope.

@pmall what are you talking about? That is not the reason why one should add a boolean value just to indicate which ticket is the latest. One simply has to query the latest status added to the table.

@terumi I'm sorry but you have been misinformed. Allow me to help and answer a few of your questions

I get an error exception "Trying to get property of non object" on this line, in Ticket model: This is because you are creating a scope and trying to query on top of $this:

//This is wrong because there is no object instantiated, hence the error
return $this->getStatusAttribute() == $type;

And instead a scope should look like this:

public function scopeCurrentStatus
{
    return $query->... and so on;
}

Scopes are used for chaining to filter the model. Scopes should always return a collection of the same Model the scope was created in. In your case you don't want a collection of Statuses/Tickets instead you just want an item that item being the latest Ticket inserted into the database

So instead create a method like so:

//TicketModel
public static function currentStatus
{
    $ticketModel = \DB::table('ticketModels')
                    ->latest() //Will order the whole set from latest to oldest.
                    ->limit(1) // limit the entry to 1 row
                    ->first(); // Use first() to get an item instead of using get() which returns a collection
    $currentStatus = $ticketModel->current_status; //name of the attribute on your TicketModel
    return $currentStatus;
}

Now you can filter the TicketModel based on the current_status like so:

        $currentStatusTickets = Ticket::where('current_status', TicketModel::currentStatus())->get();

I hope I have understood your question properly. Either way, I believe I was close, what I have written will help you understand a lot more about how scopes and queries work. If this helps, please do mark the answer as correct.

Thank you

Pavan

PavanKataria left a reply on Most Used Tags In Many-to-Many Relation

@ftiersh So this currently isn't possible in Eloquent's query builder, since the methods aren't there for complex filtering on the SQL where you want to harness orderBy, groupBy, and most importantly chain the count command. Luckily this is possible with the Database Query builder. Now before we get onto that, you mentioned that you are not using polymorphism, and that instead you have a table for each category. candidate_tags table, file_tags table. So when you wish to answer your question of I'd like to display the top 5 most tags for that relation then you'll have to query the tables separately. Of course you know this.

In pseudocode, you want this:

1) Count all tags within the relational table
2) group the tag count by the `tag_id` used in the seggragated relation table that you have. This will cause your count to split up into the tag type, and then
3) order by the the count
4) limit query to grab only 5 rows

This is what it will look like in code:

>>> \DB::table('candidate_tags')
    ->select(DB::raw('count(*) as tag_count, tag_id'))
    ->groupBy('tag_id')
    ->orderBy('order_count', 'desc')
    ->limit(5)
    ->get();
[
  {
    "tag_count": 2896,
    "tag_id": 3
  },
  {
    "tag_count": 2320,
    "tag_id": 1
  },
  {
    "tag_count": 2123,
    "tag_id": 23
  },
  {
    "tag_count": 1529,
    "tag_id": 61
  },
  {
    "tag_count": 1407,
    "tag_id": 4
  }
]```

PavanKataria left a reply on Return A Relationship Depending On Value Of A Model's Property

@BenG you're getting a funky error.

In my opinion you shouldn't be filtering the result set on your relationships. The point of the relationship definition is to do what it was meant for, to map properly the related tables and how it references to it. Remember, the query builder is only building a query to be executed at a later point. So you don't need to worry that the whole data set is being returned which is why I assume you're filtering in your relationship itself. Which brings me onto the next point.

Filtering your Order model dependant on a attribute of that model will work best when you query using a where clause. Another developer working on your project won't be expecting for there to be a filter applied, and by practise would apply the filter while building the query. Before we get into that let's talk about your scenario first and how to set your relationships up properly so that you eager load works well.

The two models we are dealing with are Order and PaymentType. This leads me to believe that a PaymentType can have many Orders, and an Order belongs to a PaymentType. It makes sense for the foreign key to lie in the Order model. I presume you have this setup for the two tables in question.

//Order
- id
- payment_type_id
//Payment Type
- id
...

So your relationship in your Order to PaymentType currently set to hasOne is wrong. It should rather be defined like so:

public function paymentTypes()
{
    return $this->belongsTo(App\PaymentType::class);
}

And in your PaymentType model you can have:

public function orders()
{
    return $this->hasMany(App\Order::class);
}

Now that you have all the ground work in place we can move onto what the query will look like when you are querying on your Order model. We need to use the whereHas method to add further constraints in our query like so:

 Order::whereStatus(2)
    ->with('paymentType')
    ->get(); 

And that's all. Here's a side point for you, I wouldn't have magic numbers like that, in the future one may ask, what is 2? It makes your code hard to read especially if that number signifies a certain status.

In my Order class, (Yes, I too am working with Orders ;) ) I have constants defined like so:

//Order
const CREATED = 1;
const PROCESSING = 2;
const ALL_DISPATCHED = 3;
const FINALISED = 4;
const CLOSED = 5;
/*
 * //Previously
 * Order::whereStatus(2)
 *    ->with('paymentType')
 *    ->get(); 
 */
// Updated cleaner version
 
Order::whereStatus(Order::PROCESSING)
    ->with('paymentType')
    ->get(); 

PavanKataria left a reply on Scope, Method Not Found

@cristian9509 This won't work because you've defined the scope in your Model class yet you are trying to access the scope from the UserType scope.

You'd want to access the scope by writing the correct model like so:

Model::slug()->get();

PavanKataria left a reply on Multiple Quires In Model Scope Function

@sufi could you explain what you are trying to do overall so we can understand better the reason for you wanting to run two queries.

PavanKataria left a reply on Store Attributes To A Model In A Separate (flexibel) Table

I'm glad to hear it @stefr. If it helped you, don't forget to mark the answer please!

Thank you.

Pavan

PavanKataria left a reply on Store Attributes To A Model In A Separate (flexibel) Table

Hi @stefr You're right in thinking that you won't need to make any changes to your existing tables since you can define the relationship by creating a new table which will have a column that references to the parent. Does every model only have one user setting or can the model have more than one user setting? Use this: if the Model can only have one UserSetting:

public function setting()
{
    return $this->has(App\UserSettings::class);
}

Or use this if the Model can have more than one UserSetting:

public function settings()
{
    return $this->hasMany(App\UserSettings::class);
}```

Also you mentioned this to another fellow:
> This doesn't work. I think with $test->settings['website'];
This won't work and that's not because of the reasons you think. 
You have an instance of your `Model` and then you can access the relationship method like so
`$model->settings();`
This returns either an item or a collection depending on how you defined the relationship. 
Most likely it will be a collection since you mentioned a `hasMany` relationship having been defined.
So you would do something like this to access the website:

foreach($settings as $setting){ $website = $setting->website; }``` And you do whatever you want. I hope this explains a few things for you.

PavanKataria left a reply on Solve The Player Controls Over Video Issue.

Switch to full screen, my friend, anyone actually, for that matter :) You seem to have the video covering your entire window anyway. lol

PavanKataria left a reply on Eagerload Multiple Nested Relations In The Same Call

You can only eager load objects that have relationships defined between the models. They must be linked in a way for you to be able to eager load the children. I believe you understand this. I presume that your Movie model branches into two different relationships like below:

  1. A Movie->hasMany:Actor
  2. A Movie->hasMany:Genre

If your Movie does branch into two like above then you will need to eager load them seperately like so:

App\User::with('movie_lists.movies.actors')
->with('movie_lists.movies.genres');
->find(1);

PavanKataria left a reply on Custom Pivot Vs New Model

  1. What is a customer order item position? Is it a reference number?
  2. Where did 02 come from for the order_item_id, I know it was an example.
  3. Could you explain in detail what the custom options will hold?

p.s. Why is the order_item_id indented? Mistake?

16 Sep
3 years ago

PavanKataria left a reply on INNER Join

@Liosva I'm glad you are now using the belongsToMany method, this is what the issue was before. :) If you could mark my answer as correct I would appreciate it. Thank you.

Pavan

PavanKataria left a reply on INNER Join

In php i use this sql : SELECT * FROM objects INNER JOIN user_objects ON objects.id=user_objects.id_object and user_objects.id_user= 1 ; It is possible to make something similar to this on laravel

@Liosva Take a look at my message, you don't need to do the above in Laravel if you set everything up properly as I described. :) The belongsToMany relationship definition will take care of this query for you ;)

PavanKataria left a reply on INNER Join

@PLB-RR Hi, I've read your answer, the inverse for a belongsToMany relationship is not hasMany as you've defined in your example User model, it is again, a belongsToMany definition that should be used.

PavanKataria left a reply on INNER Join

It looks like you're trying to setup a many-to-many relationships based on the fact that you have a user_objects table. Many-to-many relationships are defined by using the belongsToMany method in both models.

So your User model should have a relationship defined to the Objects table like so:

public function objects()
{
    /** 
     * you dont need to pass in extra parameters providing you're following
     * the column naming conventions, which you're not. More on that down below.
     */
    return $this->belongsToMany(App\Objects::class);
}

You'd do the same within the Object model but making the appropriate references to the Users table. Do this if you're interested in doing $object->users.

Pointers:

  1. You're making it more difficult for yourself by inputting extra parameters to explicitly define the correct references when you created your hasMany relationships. You've got column names such as: id_user and id_object, instead Laravel does magical things for you where it will assum the relationship name to be the model_name + _id, so if you define your column names in your pivot user_objects table with user_id, and object_id, you won't then have to provide extra foreign and local keys into your relationship definition, as I have shown in my example where I just needed to pass the name of the model.

  2. Looking at your example it is clear that you're only interested the objects associated to the user, so if you follow the conventions properly then you will realise that for this occasion you won't need to access the pivot table directly as you are. Instead you'll be able to do this $user->objects within your foor loop.

  3. change the name of the pivot table from user_objects to object_users. Laravel will automatically save into the correct pivot table so long as you name your pivot table properly: following the convention of sorting your two models my alphabet order, and then pluralising the second model. thus creating object_users instead of user_objects.

15 Sep
3 years ago

PavanKataria left a reply on Bill Of Materials Pattern And Models

Hey, great! No problem, I was just helping. I'm glad it worked for you.

I MUST :) put your name in the acknowledgments so that people know that it was your solution. Can I?

LOL, you don't have to but sure, if you like you can just link to this page ;) ;p Just for fun, tell them to like this comment, so I can see how many developers see your acknowledgement in the codebase ;p

Good luck,

Pavan.

PavanKataria left a reply on Bill Of Materials Pattern And Models

oh I see, good question. that’s okay :) since the client can have either a `produ model or `bund model then this means that relationship should also be polymorphic. This will enable you to assign more than one type of model to the client :)

So create a polymorphic relationship on the client model ​as well​. To reiterate it's so that you can save either a a `pro model or a a `bu model into your client.

PavanKataria left a reply on Bill Of Materials Pattern And Models

You can’t have an addon model or a plan model if you don’t have a table for them :simple_smile: It doesn't make sense since the model is there to act on behalf of the table. From your current design it seems that an an `a or a a ` are considered as a type of of `pro.

So I assume then that a bundles work like this:

bundle2 = plan1 + bundle1;```

This then actually translates to this:
*Products table:*

Product 1 = (addon1); Product 2 = (addon2) Product 3 = (plan1)```

And so then you should do the bundles table like this:

bundles table

- imageable_a_id  //polymorph relationship to either products or itself bundles table
- imageable_a_type //Model type tells Laravel which table to take product from.

- imageable_b_id //polymorph relationship to either products or itself bundles table
- imageable_b_type //Model type```


*Example content:*
*Bundle 1*  = `addon 1` + `addon 2`, here’s how that's stored:
```- id = 1,  
imageable_a_type = ‘products’, imageable_a_id = 1, 
imageable_b_type = ‘products’, imageable_b_id = 2```

*Bundle 2*  = `Plan 1` + `bundle 1`, here’s how that's stored:
```- id = 2,  
imageable_a_type = ‘products’, imageable_a_id = 3, 
imageable_b_type = ‘bundles’, imageable_b_id = 1```

PavanKataria left a reply on Bill Of Materials Pattern And Models

Hey,

Laravel models are not able to manage composite primary key. What makes you say that Laravel cannot handle composite keys?

It is in fact possible to create composite keys. You write something like this in your migrations file

$table->primary(array('first', 'last'));

Take a look at the documentation: http://laravel.com/docs/4.2/schema#adding-indexes

16 Jul
3 years ago

PavanKataria left a reply on A Big Thank You To Taylor

Thank you luceos for inviting me to write here.

So, Taylor, I caught up on the twitter drama hype today morning. Blasphemous!

I can understand how discouraging and demotivating it might be when dealing with people who don't appreciate, or people who suck out your energy by not being constructive and helpful. I go with the attitude of, "hey, no problem." and move on. Everyone goes through bad moments, don't live in them. It's the people who pick themselves up very quickly after a bad moment and continue on their day with positivity that do well; i.e. maintaining a positive mental attitude.
Taylor, all is well!

I don't think your spirits need to be lifted, but I hope you don't mind me taking a moment to say thank you for the awesome work that you have done. My business has been working so efficiently now since I've joined the Laravel community. You can't imagine the setup I had before and how much it slowed me down, the code wasn't scalable, I of course didn't know the best practises at the time. Now, things have improved for the better in my end since I networked with the guys who also use Laravel.

Using Laravel has made me become a better programmer. Here's the following features I'm grateful for:

  1. The documentation. The documentation is one of a kind! It's so beautiful, every single sub header has an example. The technicals are explained, even the most advanced niche features have an example JUST incase there's a person who may find it helpful.

  2. The Eloquent ORM included with Laravel and migrations. Sighs. Beautiful. I was a spaghetti programer 3 years ago for server side API building, and it was hard to maintain. Since joining the Laravel community, I Instantly made the decision to port everything over. The migration is nearly complete, and I forecast scalable code! Man, my clients will be happy to know that I can meet all of their challenging requirements (which required database changes) very easily now with Eloquent and migrations

  3. Form requests and Validation classes. How awesome are these. I love the abstraction, and I love how they're reusable for different routes. It makes my controller classes very clean.

  4. Continual improvements and implementation of new features to the Laravel framework. This gives me hope that Laravel will truly be at the forefront with it's aim of being a truly easy to use framework for anyone, while being able to keep up with emerging technologies and concepts. Take for example Broadcasting. I haven't tried it out yet, but it's a cool feature for 5.0!

I'm still exploring Laravel so there will be many more things that I will learn and come to love.

The point is, I appreciate your work Taylor, without it, I might have still been writing spaghetti server side code for my mobile applications. :)

Pavan iOS developer