trifek

trifek

Member Since 11 Months Ago

Experience Points
520
Total
Experience

4,480 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
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
520 XP
May
31
22 hours ago
Activity icon

Replied to Building A Form With Laravelcollective

why is it better to avoid building forms? Is it better to stack them manually?

May
30
1 day ago
Activity icon

Replied to Building A Form With Laravelcollective

why is it better to avoid building forms? Is it better to stack them manually?

With checkbox I need something like this:

@if(!empty($page) && $page->enable == '1') checked="checked" @endif

but I don't know how to write it in form builder:(

btw. what are your good and bad points about form builders?

Activity icon

Started a new Conversation Building A Form With Laravelcollective

Hi, I have project written in Laravel 7. I use https://laravelcollective.com/docs/6.0/html to build forms.

I have this code:

{!! Form::open(['route' => ['page.store'], 'method' => 'POST', 'class' => 'form form-horizontal form-bordered', 'files' => false]) !!}
                    <div class="card-body">
                        <div class="form-group row">
                            {{Form::label('title', 'Tytuł strony tekstowej*', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12">
                                {{Form::text('title', $page->title ?? old('title'), ['maxlength' => 155, 'required' => 'required', 'class' => 'form-control', 'placeholder' => 'Wpisz tytuł strony tekstowej*'])}}
                            </div>
                        </div>
                        <div class="form-group row">
                            {{Form::label('description', 'Description', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12">
                                {{Form::text('description', $page->description ?? old('description'), ['maxlength' => 155, 'class' => 'form-control', 'placeholder' => 'Wpisz description'])}}
                            </div>
                        </div>
                        <div class="form-group row">
                            {{Form::label('keywords', 'Keywords', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12">
                                {{Form::text('keywords', $page->keywords ?? old('keywords'), ['maxlength' => 155, 'class' => 'form-control', 'placeholder' => 'Wpisz keywords'])}}
                            </div>
                        </div>
                        <div class="form-group row">
                            {{Form::label('content', 'Treść strony tekstowej', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12">
                                {{Form::textarea('content', $page->content ?? old('content'), ['class' => 'form-control summernote', 'placeholder' => ''])}}
                            </div>
                        </div>
                        <div class="form-group row">
                            {{Form::label('content', 'Wpis aktywny', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12 ">
                                <label class="switch ">
                                    {{ Form::checkbox('enable', '1', true, ['class'=>'default']) }}
                                    <span class="slider round"></span>
                                </label>
                            </div>
                        </div>
                        <div class="form-group row">
                            <div class="col-lg-2"></div>
                            <div class="col-lg-10">
                                {{Form::submit('Zapisz', ['class' => 'btn btn-primary mr-2'])}}
                            </div>
                        </div>
                    </div>
                    {!! Form::close() !!}

I have a problem with the checkbox. It is always selected (regardless of whether the record is $page->enable == '1' or $page->enable == '0').

How can I fix it?

I try make something like this:

<div class="form-group row">
                            {{Form::label('content', 'Wpis aktywny', ['class'=>'col-form-label text-left col-lg-2 col-sm-12'])}}
                            <div class="col-lg-10 col-sm-12 ">
                                <label class="switch ">
                                    {{ Form::checkbox('enable', $page->enable, true, ['class'=>'default']) }}
                                    <span class="slider round"></span>
                                </label>
                            </div>
                        </div>

but it's return me error: $page is undefined

Make the variable optional in the blade template. Replace {{ $page }} with {{ $page ?? '' }}

How can I fix it?

I have second questions. I would like to have 1 form to edit and add a new record.

Is this solution optimal / correct:

@if($page ?? '' ?? false)
                            {!! Form::open(['route' => ['page.update', ['id' => $page->id ?? null]], 'method' => 'PUT', 'class' => 'form form-horizontal form-bordered', 'files' => false]) !!}
                    @else
                            {!! Form::open(['route' => ['page.store'], 'method' => 'POST', 'class' => 'form form-horizontal form-bordered', 'files' => false]) !!}
                    @endif

?

May
25
6 days ago
Activity icon

Started a new Conversation Change Location Auth Classes

I make project in Laravel 7. I change location Http\Controllers\Auth to Http\Controllers*Admin*\Auth

In all files in Auth directory I change namespaces:

from:

    namespace App\Http\Controllers\Auth;

to

    namespace App\Http\Controllers\Admin\Auth;

Them I make composer dump-autoload.

Login work fine.

Now when I try logout with my code:

    <a href="{{ route('logout') }}"
                           onclick="event.preventDefault(); document.getElementById('logout-form').submit();" class="btn btn-sm btn-light-primary font-weight-bolder py-2 px-5">Wyloguj</a>
                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                            @csrf
                        </form>

I have error:

Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\Front\Auth\LoginController] does not exist.

My RouteServiceProvider:


    class RouteServiceProvider extends ServiceProvider
    {
        /**
         * This namespace is applied to your controller routes.
         *
         * In addition, it is set as the URL generator's root namespace.
         *
         * @var string
         */
        protected $namespace = 'App\Http\Controllers';
    
        /**
         * The path to the "home" route for your application.
         *
         * @var string
         */
        public const HOME = '/';
    
        /**
         * Define your route model bindings, pattern filters, etc.
         *
         * @return void
         */
        public function boot()
        {
            //
    
            parent::boot();
        }
    
        /**
         * Define the routes for the application.
         *
         * @return void
         */
        public function map()
        {
            $this->mapApiRoutes();
    
            if(config('app.admin_only'))
            {
                $this->mapAdminOnlyRoutes();
            }
            else
            {
                $this->mapWebRoutes();
                $this->mapAdminRoutes();
            }
        }
    
        /**
         * Define the "web" routes for the application.
         *
         * These routes all receive session state, CSRF protection, etc.
         *
         * @return void
         */
        protected function mapWebRoutes()
        {
            Route::middleware('web')
                ->namespace($this->namespace. '\Front')
                ->group(base_path('routes/web.php'));
        }
    
        /**
         * Define the "api" routes for the application.
         *
         * These routes are typically stateless.
         *
         * @return void
         */
        protected function mapApiRoutes()
        {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
        }
    
        protected function mapAdminRoutes()
        {
            Route::prefix(config('app.admin_prefix'))
                ->middleware('web')
                ->namespace($this->namespace.'\Admin')
                ->group(base_path('routes/admin.php'));
        }
    
        protected function mapAdminOnlyRoutes()
        {
            Route::middleware('web')
                ->namespace($this->namespace. '\Admin')
                ->group(base_path('routes/admin.php'));
        }
    }

My files structure:

  • App\Http\Controllers\Admin\Auth - auth files
  • App\Http\Controllers\Admin\ - admin files
  • App\Http\Controllers\Front\ - website files

admin.php:

Route::name('admin.')->group(function(){
	Auth::routes(['register' => false, 'reset' => false, 'confirm' => false, 'verify' => false]);

    Route::get('/', '[email protected]')->name('home');

	......
});

Route::group(['prefix' => '', 'middleware' => 'auth'], function () {
//    Route::prefix('admin') ->middleware('auth') ->group(function () {
    /* Pages */
    Route::get('/pages', '[email protected]')->name('page.index');
    Route::get('/pages/create', '[email protected]')->name('page.create');
    Route::post('/pages/store', '[email protected]')->name('page.store');
    Route::get('/pages/edit' . '/{id?}', '[email protected]')->name('page.edit');
    Route::put('/pages/update' . '/{id?}', '[email protected]')->name('page.update');
    Route::delete('/pages/destroy' . '/{id?}', '[email protected]')->name('page.destroy');

   .....

});

web.php

Route::get('/', '[email protected]')->name('home');
//Route::get('/admin', function () { return view('admin.home'); })->name('admin.home');
Auth::routes(['verify' => true]);

What is wrong? How can I repair it?

May
24
1 week ago
Activity icon

Replied to Cache In Laravel

Yes, it's all :) Thank. you. How can I mark this thread as solved?

Activity icon

Replied to Cache In Laravel

Thank you very much :) It's working :)

How would you organize such deleting of many caches in different methods? Or it's okey?

public function create (array $ data): int
    {
        $ This-> cache-> remove ($ this-> cacheKey);
        $ This-> cache-> remove ($ this-> cacheKey.. 'All');
        $ This-> cache-> remove ($ this-> cacheKey.. "Enables');
        $ This-> cache-> remove ($ this-> cacheKey.. 'Letter');
        $ This-> cache-> removePagination ($ this-> cacheKey.. 'Search.');
        $ This-> cache-> removePagination ($ this-> cacheKey. '. ListWithPaginate.');
        return $ this-> model-> create ($ data) -> id;
    }

    public function update (array $ data, int $ id, string $ attribute = 'id'): void
    {
        $ This-> cache-> remove ($ this-> cacheKey.. "$ {Id}");
        $ This-> cache-> remove ($ this-> cacheKey);
        $ This-> cache-> remove ($ this-> cacheKey.. 'All');
        $ This-> cache-> remove ($ this-> cacheKey.. "Enables');
        $ This-> cache-> remove ($ this-> cacheKey.. 'Letter');
        $ This-> cache-> removePagination ($ this-> cacheKey.. 'Search.');
        $ This-> cache-> removePagination ($ this-> cacheKey. '. ListWithPaginate.');

        $ this-> model-> where ($ attribute, '=', $ id) -> update ($ data);
    }

    public function delete (int $ id): void
    {
        $ This-> cache-> remove ($ this-> cacheKey.. "$ {Id}");
        $ This-> cache-> remove ($ this-> cacheKey);
        $ This-> cache-> remove ($ this-> cacheKey.. 'All');
        $ This-> cache-> remove ($ this-> cacheKey.. "Enables');
        $ This-> cache-> remove ($ this-> cacheKey.. 'Letter');
        $ This-> cache-> removePagination ($ this-> cacheKey.. 'Search.');
        $ This-> cache-> removePagination ($ this-> cacheKey. '. ListWithPaginate.');

        $ This-> model-> destroy ($ id);
    }
Activity icon

Replied to Cache In Laravel

Thank you so much for your help and patience. My previous topic is solved correctly. (from yesterday) Now, if this problem is solved, I will convert my code to a repozitory-free pattern. At the moment I must have to run it on actual form what I have now :(

When I'm debbug in CachingBaseRepository:

public function delete(int $id): void
    {
dd($this->cache);
        $this->cache->removePagination($this->cacheKey);
        $this->cache->removePagination($this->cacheKey.'.listWithPaginate');
        $this->cache->remove($this->cacheKey);
        $this->cache->remove($this->cacheKey.'.listWithPaginate');
....
}

I have return: null.

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

thank you very much for your's help :)

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

the solution with is problem was change $this->model:

class CachingCategoryRepository extends CachingBaseRepository implements CategoryRepositoryInterface

{
    public function __construct(CategoryRepositoryInterface $model)
    {
        $this->model = $model->getModel();
        $this->cacheKey = 'category';
        $this->cacheTime = 3600;
    }
}
Activity icon

Replied to Cache In Laravel

Yes, I have:

use App\Repositories\Interfaces\RepositoryInterface;
use App\Traits\ScopeActiveTrait;
use Cache;
use App\Services\CacheService;


abstract class CachingBaseRepository implements RepositoryInterface
{
    use ScopeActiveTrait;

    protected $model;
    protected $cacheKey;
    protected $cacheTime;
    protected $cache;

    public function __construct(CacheService $cache)
    {
        $this->cache = $cache;
    }
...
}

but it's not helping

Activity icon

Replied to Cache In Laravel

thank you.

I make this code:

public function update(array $data, int $id, string $attribute = 'id'): void
    {
        $this->model->where($attribute, '=', $id)->update($data);
        $this->cache->removePagination($this->cacheKey);
        $this->cache->removePagination($this->cacheKey.'.listWithPaginate');

        $this->cache->remove($this->cacheKey);
        $this->cache->remove($this->cacheKey.'.listWithPaginate');
//        Cache::forget($this->cacheKey);
//        Cache::forget($this->cacheKey.".{$id}");
//        Cache::forget($this->cacheKey.'.all');
//        Cache::forget($this->cacheKey.'.enables');
//        Cache::forget($this->cacheKey.'.list');
//        Cache::forget($this->cacheKey.'.listWithPaginate');
    }

but it's not working. I hav error: Call to a member function remove() on null

My $this->cacheKey - has value "page" (I check by dd($this->cacheKey) )

Activity icon

Replied to Cache In Laravel

I use cache filesystem. I can't use tags

Activity icon

Replied to Cache In Laravel

thank you. It's help. :)

At the moment I have this code:

public function listWithPaginate (string $ orderByColumn, string $ orderBy = 'desc', array $ with = [], int $ perPage = 10)
    {
        return Cache :: remember ($ this-> cacheKey. '. listWithPaginate.'. request () -> query ('page', 1), $ this-> cacheTime, function () use ($ with, $ orderByColumn, $ orderBy, $ perPage) {
            return $ this-> model-> with ($ with)
                -> orderBy ($ orderByColumn, $ orderBy)
                -> paginate ($ perPage) -> appends (request () -> query ());
        });
    }

When I edit a record, the list is inactive.

I think in this function I should add deleting changed value, yes?

public function update (array $ data, int $ id, string $ attribute = 'id'): void
    {
        $ this-> model-> where ($ attribute, '=', $ id) -> update ($ data);
        :: Cache forget ($ this-> cacheKey);
        :: Cache forget ($ this-> cacheKey.. "{$ Id}");
        :: Cache forget ($ this-> cacheKey.. 'All');
        :: Cache forget ($ this-> cacheKey. '. Enables');
        :: Cache forget ($ this-> cacheKey.. 'Letter');
        :: Cache forget ($ this-> cacheKey. '. ListWithPaginate');
    }

how to do it when eg the modified record is on page 4?

Activity icon

Started a new Conversation Cache In Laravel

Hi, I am beginner in Laravel. In my project I use repository pattern and Laravel 7.

I have this controller:


class PageController extends Controller
{

    protected $model;

    /**
     * PageController constructor.
     * @param PageRepositoryInterface $repository
     */
    public function __construct(PageRepositoryInterface $repository)
    {
        $this->model = $repository;
    }


    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->input('query') != "") {
            $pages = $this->model->search($request->input('query'), 'id', 'asc', [],  30);
        } else {
            $pages = $this->model->listWithPaginate('id', 'desc', [],  30);
        }
        return view('admin.pages.list', ['pages' => $pages]);
    }


    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('admin.pages.view');
    }


    /**
     * @param PageRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(PageRequest $request)
    {
        if ($request->isMethod('post')) {
            $data = [
                'title' => $request->input('title'),
                'description' => $request->input('description') ?? $request->input('title'),
                'keywords' => $request->input('keywords') ?? $request->input('title'),
                'content' => $request->input('content'),
                'enable' => $request->input('enable') ?? 0,
                'slug' => Str::slug($request->input('title'), '-')
            ];
            $this->model->create($data);
            return redirect()->route('page.index')->with('success', __('messages.record_save_info'));
        }
    }


    /**
     * @param int $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(int $id)
    {
        Cache::forget("page.{$id}");
        return view('admin.pages.view', ['page' => $this->model->findOrFail($id)]);
    }


    /**
     * @param PageRequest $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(PageRequest $request, int $id)
    {
        if ($request->isMethod('put')) {
            $data = [
                'title' => $request->input('title'),
                'description' => $request->input('description'),
                'keywords' => $request->input('keywords'),
                'content' => $request->input('content'),
                'enable' => $request->input('enable') ?? 0,
                'slug' => Str::slug($request->input('title'), '-')
            ];
            $this->model->update($data, $id, 'id');
            return redirect()->route('page.index')->with('success', __('messages.record_edit_info'));
        }
    }


    /**
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request, int $id)
    {
        if ($request->isMethod('delete')) {
            $this->model->delete($id);
            return redirect()->route('page.index')->with('success', __('messages.record_remove_info'));
        }
    }
}

and CachingBaseRepository

abstract class CachingBaseRepository implements RepositoryInterface
{
    use ScopeActiveTrait;

    protected $model;
    protected $cacheKey;
    protected $cacheTime;

    public function all()
    {
        return Cache::remember($this->cacheKey.'.all', $this->cacheTime, function () {
            return $this->model->get();
        });
    }

    public function allEnables()
    {
        return Cache::remember($this->cacheKey.'.enables', $this->cacheTime, function () {
            return $this->model->active()->get();
        });
    }

    public function list(string $orderByColumn, string $orderBy = 'desc', array $with = [])
    {
        return Cache::remember($this->cacheKey.'.list', $this->cacheTime, function () use($with, $orderByColumn, $orderBy) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->get();
        });
    }

    public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return Cache::remember($this->cacheKey.'.listWithPaginate', $this->cacheTime, function () use($with, $orderByColumn, $orderBy, $perPage) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->paginate($perPage)->appends(request()->query());
        });
    }

    public function create(array $data): int
    {
        Cache::forget($this->cacheKey);
        Cache::forget($this->cacheKey.'.all');
        Cache::forget($this->cacheKey.'.enables');
        Cache::forget($this->cacheKey.'.list');
        Cache::forget($this->cacheKey.'.listWithPaginate');
        return $this->model->create($data)->id;
    }

    public function update(array $data, int $id, string $attribute = 'id'): void
    {
        $this->model->where($attribute, '=', $id)->update($data);
        Cache::forget($this->cacheKey);
        Cache::forget($this->cacheKey.".{$id}");
        Cache::forget($this->cacheKey.'.all');
        Cache::forget($this->cacheKey.'.enables');
        Cache::forget($this->cacheKey.'.list');
        Cache::forget($this->cacheKey.'.listWithPaginate');
    }

    public function delete(int $id): void
    {
        $this->model->destroy($id);
        Cache::forget($this->cacheKey);
        Cache::forget($this->cacheKey.'.all');
        Cache::forget($this->cacheKey.'.enables');
        Cache::forget($this->cacheKey.'.list');
        Cache::forget($this->cacheKey.'.listWithPaginate');
    }

    public function find(int $id)
    {
        return Cache::remember($this->cacheKey.".{$id}", $this->cacheTime, function () use ($id) {
            return $this->model->find($id);
        });
    }

    public function getModel()
    {
        return Cache::remember($this->cacheKey.".all", $this->cacheTime, function (){
            return $this->model;
        });
    }

    public function findOrFail(int $id)
    {
        return Cache::remember($this->cacheKey.".{$id}", $this->cacheTime, function () use ($id) {
            return $this->model->findOrFail($id);
        });
    }
}

I have problem with paginate. When I go to pagination 2,3,7 or 10 - I always see the same as on page 1.

Is my code optimal? Can duplication be replaced - one function (I have remove in controller - in edit too):

:: Cache forget ($ this-> cacheKey);
         :: Cache forget ($ this-> cacheKey.. 'All');
         :: Cache forget ($ this-> cacheKey. '. Enables');
         :: Cache forget ($ this-> cacheKey.. 'Letter');
         :: Cache forget ($ this-> cacheKey. '. ListWithPaginate');

some one function?

May
23
1 week ago
Activity icon

Replied to Error In Laravel Too Few Arguments To Function

I found problem. I make debug:

public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
...
dd($this->model);
...
}

When I have in ServiceProvider:

public function register()
    {
        $this->app->bind(
            PageRepositoryInterface::class,
            PageRepository::class
        );
    }

my debug return:

App\Models\Page {#348 ▼
  #quarded: array:1 [▶]
....

When I have new ServiceProvider

public function register()
    {
        $this->app->bind(PageRepositoryInterface::class, function ($app) {
            return new CachingPageRepository(
                new PageRepository(new Page())
            );
        });
    }

    public function provides()
    {
        return [
            PageRepositoryInterface::class,
        ];
    }

my debug return:

App\Repositories\PageRepository {#343 ▼
  #model: App\Models\Page {#344 ▼
    #quarded: array:1 [▶]
    #fillable: array:6 [▶]
Activity icon

Replied to Error In Laravel Too Few Arguments To Function

Yes, I read error messages :)

Page repository extends BaseRepository. In BaseRepository i have:

public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return $this->model->with($with)
            ->orderBy($orderByColumn, $orderBy)
            ->paginate($perPage)->appends(request()->query());
    }

CacheBaseRepository has:

public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return Cache::remember($this->cacheKey.'.listWithPaginate', $minutes = 10, function () use($with, $orderByColumn, $orderBy, $perPage) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->paginate($perPage)->appends(request()->query());
        });
    }

Before adding the cache, BaseRepository worked in its current form

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

I am try this this combination:

class CachingPageRepository extends CachingBaseRepository implements PageRepositoryInterface
{
    public function __construct(PageRepositoryInterface $model)
...
}

and:

class CachingPageRepository extends CachingBaseRepository implements PageRepositoryInterface
{
    public function __construct(PageRepository $model)
...
}

In each case the same error

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

Yes, it's help. Thank you all for your help!!! :). Now have error:

public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return Cache::remember($this->cacheKey.'.listWithPaginate', $minutes = 10, function () use($with, $orderByColumn, $orderBy, $perPage) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->paginate($perPage)->appends(request()->query());
        });
    }

in line: return $this->model->with($with)

Error:

Call to undefined method App\Repositories\PageRepository::with()

Why it's not work ?

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

"By the way, I really don't understand why people want to use repository, with eloquent I think it's not necessary."

I am taking a course and recommend using a repository

Activity icon

Replied to Error In Laravel Too Few Arguments To Function

Thank you very much for your answer.

You suggest to replace:

new PageRepository

on:

new PageRepository (new Page)

?

If so, this change causes an error::

Argument 1 passed to App\Repositories\Caching\CachingPageRepository::__construct() must be an instance of App\Models\Page, instance of App\Repositories\PageRepository given, called in /var/www/app/Providers/PageServiceProvider.php on line 23```
Activity icon

Started a new Conversation Error In Laravel Too Few Arguments To Function

Hi, I am beginner in php and Laravel. I use in my project Laravel 7. I have repository pattern in my project with cache.

PageServiceProvider:

public function register()
{
    $this->app->bind(PageRepositoryInterface::class, function ($app) {
        return new CachingPageRepository(
            new PageRepository
        );
    });
}

public function provides()
{
    return [
        PageRepositoryInterface::class,
    ];
}

CachingBaseRepository:

abstract class CachingBaseRepository implements RepositoryInterface
{
    use ScopeActiveTrait;

    protected $model;

    public function all()
    {
        return Cache::remember($this->model.'.all', $minutes = 10, function () {
            return $this->model->get();
        });
    }

    public function allEnables()
    {
        return Cache::remember($this->model.'.enables', $minutes = 10, function () {
            return $this->model->active()->get();
        });
    }

    public function list(string $orderByColumn, string $orderBy = 'desc', array $with = [])
    {
        return Cache::remember($this->model.'.list', $minutes = 10, function () use($with, $orderByColumn, $orderBy) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->get();
        });
    }

    public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return Cache::remember($this->model.'.listWithPaginate', $minutes = 10, function () use($with, $orderByColumn, $orderBy, $perPage) {
            return $this->model->with($with)
                ->orderBy($orderByColumn, $orderBy)
                ->paginate($perPage)->appends(request()->query());
        });
    }

    public function create(array $data): int
    {
        return $this->model->create($data)->id;
        // delete cache: all, enables, list, listWithPaginate
    }

    public function update(array $data, int $id, string $attribute = 'id'): void
    {
        $this->model->where($attribute, '=', $id)->update($data);
        // delete cache: all, enables, list, listWithPaginate
    }

    public function delete(int $id): void
    {
        $this->model->destroy($id);
        // delete cache: all, enables, list, listWithPaginate
    }

    public function find(int $id)
    {
        return Cache::remember($this->model.".{$id}", $minutes = 60, function () use ($id) {
            return $this->model->find($id);
        });
    }

    public function getModel()
    {
        return Cache::remember($this->model.".all", $minutes = 60, function (){
            return $this->model;
        });
    }

    public function getFirst(int $id)
    {
        return Cache::remember($this->model.".{$id}", $minutes = 60, function () use ($id) {
            return $this->model->where('id', $id)->first();
        });
    }

    public function findOrFail(int $id)
    {
        return Cache::remember($this->model.".{$id}", $minutes = 60, function () use ($id) {
            return $this->model->findOrFail($id);
        });
    }
}

BaseRepository:

abstract class BaseRepository implements RepositoryInterface
{
    use ScopeActiveTrait;

    protected $model;

    public function all()
    {
        return $this->model->get();
    }

    public function allEnables()
    {
        return $this->model->active()->get();
    }

    public function list(string $orderByColumn, string $orderBy = 'desc', array $with = [])
    {
        return $this->model->with($with)
            ->orderBy($orderByColumn, $orderBy)
            ->get();
    }

    public function listWithPaginate(string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return $this->model->with($with)
            ->orderBy($orderByColumn, $orderBy)
            ->paginate($perPage)->appends(request()->query());
    }

    public function create(array $data): int
    {
        return $this->model->create($data)->id;
    }

    public function update(array $data, int $id, string $attribute = 'id'): void
    {
        $this->model->where($attribute, '=', $id)->update($data);
    }

    public function delete(int $id): void
    {
        $this->model->destroy($id);
    }

    public function find(int $id)
    {
        return $this->model->find($id);
    }

    public function getModel()
    {
        return $this->model;
    }

    public function getFirst(int $id)
    {
        return $this->model->where('id', $id)->first();
    }

    public function findOrFail(int $id)
    {
        return $this->model->findOrFail($id);
    }
}

PageRepository:

class PageRepository extends BaseRepository implements PageRepositoryInterface
{

    public function __construct(Page $model)
    {
        $this->model = $model;
    }


    public function search(string $query, string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return $this->model->where('title', 'LIKE', '%' . $query . '%')->orWhere('description', 'LIKE', '%' . $query . '%')->orWhere('keywords', 'LIKE', '%' . $query . '%')->orWhere('content', 'LIKE', '%' . $query . '%')->with($with)->orderBy($orderByColumn, $orderBy)->paginate($perPage)->appends(request()->query());
    }

    public function getTextPageFromSlug(string $slug)
    {
        return $this->model->active()->where('slug', $slug)->first();
    }

}

CachingPageRepository

class CachingPageRepository extends CachingBaseRepository implements PageRepositoryInterface
{
    public function __construct(Page $model)
    {
        $this->model = $model;
    }


    public function search(string $query, string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 10)
    {
        return Cache::remember('page.all', $minutes = 10, function () use($query, $orderByColumn, $with, $orderBy, $perPage) {
            return $this->model->where('title', 'LIKE', '%' . $query . '%')->orWhere('description', 'LIKE', '%' . $query . '%')->orWhere('keywords', 'LIKE', '%' . $query . '%')->orWhere('content', 'LIKE', '%' . $query . '%')->with($with)->orderBy($orderByColumn, $orderBy)->paginate($perPage)->appends(request()->query());
        });
    }


    public function getTextPageFromSlug(string $slug)
    {
        return Cache::remember("users.{$slug}", $minutes = 60, function () use ($slug) {
            return $this->model->active()->where('slug', $slug)->first();
        });
    }
}

PageRepositoryInterface:

interface PageRepositoryInterface extends RepositoryInterface
{

    public function search(string $query, string $orderByColumn, string $orderBy = 'desc', array $with = [], int $perPage = 30);


    public function getTextPageFromSlug(string $slug);

}

I want to add cache to my website in the above code. My controller looks like this:

protected $model;


    public function __construct(PageRepositoryInterface $repository)
    {
        $this->model = $repository;
    }


    public function index(Request $request)
    {
        if ($request->input('query') != "") {
            $pages = $this->model->search($request->input('query'), 'id', 'asc', [],  30);
        } else {
            $pages = $this->model->listWithPaginate('id', 'desc', [],  30);
        }
        return view('admin.pages.list', ['pages' => $pages]);
    }

When I run the above code I get the error:

ArgumentCountError Too few arguments to function App\Repositories\PageRepository::__construct(), 0 passed in /var/www/app/Providers/PageServiceProvider.php on line 22 and exactly 1 expected

Earlier, when I didn't have the cache on the page, my PageServiceProvider looked like this:

public function register()
    {
        $this->app->bind(
            PageRepositoryInterface::class,
            PageRepository::class
        );
    }

And the code ran without problems.

How can I repair it?

Please help me.

Dec
13
5 months ago
Activity icon

Started a new Conversation Links() Not Working In Laravel 5.8

Hi, I'a beginner in Laravel. I use Laravel 5.8 in my project.

I have problem with pagination.

I have this code:

class ForumCategory extends Model
{
    use scopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['company_id', 'enable', 'name', 'url_address', 'enable'];
    public $timestamps = false;

    public function themes()
    {
        return $this->hasMany('App\ForumPost', 'id_category', 'id')->where('parent_id', '=', null);
    }

    public function lastPost()
    {
        return $this->themes()->orderBy('id', 'desc')->first();
    }
}

class ForumPost extends Model
{
    use scopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['company_id', 'id_category', 'parent_id', 'user_id', 'date', 'title', 'content', 'url_address', 'enable'];
    public $timestamps = true;
    protected $table = 'forum';

    public function category()
    {
        return $this->belongsTo('App\ForumCategory', 'id_category');
    }

    public function author()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function postCount()
    {
        return $this->hasMany('App\ForumPost', 'parent_id', 'id')->where('parent_id', '!=', null)->count();
    }
}



@foreach ($forums as $forum)
Welcome in {{ $forum->name }}<br/>
    @foreach ($forum->themes as $post)
      Post: {{ $post->title }}
<div class="paginationFormat"></div>
<div class="text-right">{{ $post->links() }}</div>
@endforeach
<div class="paginationFormat"></div>
<div class="text-right">{{ $forums->links() }}</div>
@endforeach

I run this code by function:

public function getForumCategories()
    {
        $forumCategories = ForumCategory::with('themes')->orderBy('name', 'asc')->paginate(1);
        if(!$forumCategories->isEmpty()) {
            foreach ($forumCategories as $category) {
                $category->setRelation('themes', $category->themes()->paginate(1));
            }
        }
        return $forumCategories;
    }

I need pagination in $post.

In my code I have error:

Call to undefined method App\ForumPost::links() (View: ....)

How can I repair it?