Home > database >  Get Laravel collection's item using collection value
Get Laravel collection's item using collection value

Time:02-10

Suppose we got a collection from the database like this:

$projects = Projects::all();

Now, for example, I want to get the specific project using the specified column's value. For example, suppose any project has a unique pr_code, Now I want to get an item of collection that pr_code is 1234.

Note = I Know using Projects::where('pr_code', 1234)->first() But I didn't want this. I want use inside collection

How I could do that?

CodePudding user response:

Collections also have where and first (and whereFirst ) functions. So you just need to change the order of functions in your chain: Projects::all()->firstWhere('pr_code', 1234)

CodePudding user response:

Projects::all() queries all records in projects and returns them as a Collection of Projects models, this could be quite a performance hit.

Projects::where('pr_code', 1234)->get() will query for the specific projects and return a Collection of Projects models that have pr_code of 1234.

Projects::where('pr_code', 1234)->first() will do the same, but return the first as a Projects model.

I recommend naming the model Project rather than the plural Projects. The Laravel model is smart enough to know to use the plural name of the database table.

  • Related