3

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?

2
  • 4
    $projects = Projects::where('pr_code', 1234)->first(); Commented Feb 8, 2022 at 18:06
  • 1
    I don't understand your note. Please show an example Commented Feb 8, 2022 at 18:42

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.