How to streamline the relationship there are many that are streamlined?

I would like to paginate the following relationships (a category with many applications):

class Category extends Model
{
    public function apps()
    {
        return $this->hasMany('App\App')->orderBy('current_price', 'asc');
    }
}

The problem is that when I add ->paginate(10);to the end of this line, I get the following error:

The relationship method should return an object of type Light \ Database \ Eloquent \ Relations \ Communication

What am I missing here?

+4
source share
2 answers

Have you tried this?

$category = Category::first();
$apps = $category->apps()->paginate(10);
return view('example', compact('category', 'apps'));

Then, in your opinion, you can simply scroll through the applications.

@foreach ($apps as $app)
    {{ $app->id }}
@endforeach

{!! $apps->render() !!}

If you want to set it as a category, you can use the method setRelation:

$category = Category::first();
$category->setRelation('apps', $category->apps()->paginate(10));
return view('example', compact('category');

Then, in your opinion:

@foreach ($category->apps as $app)
    {{ $app->id }}
@endforeach

{!! $category->apps->render() !!}
+8

, " ". .

.

App\\ReportsRepository

.

namespace App\Repositories;

use App\User;

class ReportsRepository
{
    public function findByUser(User $user, $paginate = 10)
    {
        $reports = User::find($user->id)
            ->reports()
            ->orderBy('created_at', 'DESC')
            ->paginate($paginate);
        return $reports;
    }
}

ReportController

ReportRepositroy ( Auth).

class ReportController extends Controller
{
    public function index(\App\Repositories\ReportsRepository $repo)
    {
        $reports = $repo->findByUser(Auth::user());
        return view('report.index', ['reports' => $reports]);
    }
}

- report/index.blade.php

{!! $reports- > render()!!}. .

@extends('layout.master')

@section('content')
    <div class="content">
        <h1>Reports</h1>

        @if ($reports->count())
            <table class="table">
                <thead>
                    <tr>
                        <th>Status</th>
                        <th>Info</th>
                        <th>Date</th>
                    </tr>
                </thead>

                <tbody>
                @foreach($reports as $report)
                    <tr class="{{ $report['status'] }}">
                        <td>{{ $report['status'] }}</td>
                        <td>{{ $report['info'] }}</td>
                        <td>{{ $report['created_at'] }}</td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        @else
            <p>No records exist.</p>
        @endif

        {!! $reports->render() !!}

    </div>
@stop

, . Laravel .

, .

+1

Source: https://habr.com/ru/post/1614338/


All Articles