0

I can echo all data form this array but how can I get fetch the first data and second data separately? I echo this get all user_id, I want to separately save user_id in somewhere.

    <?php
        use App\AssignSubmission;

        $user = auth()->user();
        $AssignSubmissions = AssignSubmission::with('submissions')->where('user_id', $user->id)->get();
    foreach ($AssignSubmissions as $AssignSubmission)
    {
        echo $AssignSubmission->submissions->user_id;
    }
    ?>
5
  • Your question is not clear. What are the two data ? Commented Oct 28, 2018 at 4:14
  • I can echo all data from this array but now I only want to echo the specific data I want Commented Oct 28, 2018 at 4:16
  • Try like this echo $AssignSubmission->submissions[0]->user_id;. echo $AssignSubmission->submissions->[1]user_id; Commented Oct 28, 2018 at 4:54
  • Use the ->limit(2)->get() to limit your query. Then echo all items in your foreach Commented Oct 28, 2018 at 4:54
  • @AmolRokade ->submissions looks like it's a relation, not a array or am I missing some advanced Laravel syntax? :) Commented Oct 28, 2018 at 4:56

1 Answer 1

1

->submissions is a relation, so you can easily limit the number of items you're getting with the query builder using ->limit(2) before the ->get(). Then only the first 2 get loaded.

If you need all others as well, then you might instead want to use a counter inside your foreach that will trigger a break; call inside a if statement inside the foreach loop:

var $cnt = 0;
foreach(....) {
    $cnt++;
    if ($cnt > 2) break;
    ...
}

For more information, have a look at Laravel's documentation on:

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

2 Comments

yes it is relation what if I just want the 2nd data
Use ->offset(1)->limit(1)->get(). This is all in Laravel’s excellent documentation on Database, have a look there for more details and info.

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.