Module Access User Repo

Hey does anyone have some knowedlge on getting a custom module to talk with the UserRepo? I created a module, added the Repo as it was add on the frontend users listing. But I am getting nothing. When I try to print the array it comes back as php memory exceeded, however I do not believe its a php memory issue. My code for the module controller is:

 

<?php

namespace Modules\Staff\Http\Controllers\Admin;

use App\Contracts\Controller;
use App\Models\Enums\UserState;
use App\Repositories\Criteria\WhereCriteria;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use League\ISO3166\ISO3166;
use Prettus\Repository\Exceptions\RepositoryException;
/**
 * Class AdminController
 * @package Modules\Staff\Http\Controllers\Admin
 */
class AdminController extends Controller
{
  private $userRepo;

  /**
   * @param UserRepository $userRepo
   */
  public function __construct(UserRepository $userRepo)
  {
      $this->userRepo = $userRepo;
  }


    public function index(Request $request)
    {
      $where = [];

      if (setting('pilots.hide_inactive')) {
          $where['state'] = UserState::ACTIVE;
      }

      try {
          $this->userRepo->pushCriteria(new WhereCriteria($request, $where));
      } catch (RepositoryException $e) {
          Log::emergency($e);
      }

      $users = $this->userRepo
      ->with(['airline', 'current_airport'])
          ->orderBy('pilot_id', 'asc');

          return view('staff::admin.index', [
              'users' => $users,
          ]);

    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('staff::admin.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
    }

    /**
     * Show the specified resource.
     */
    public function show()
    {
        return view('staff::admin.show');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit()
    {
        return view('staff::admin.edit');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy()
    {
    }
}

Any help would be appreciated!

Not sure if it’s the right way of doing it, but I’ve had success doing it like this:

private $userRepo; /\*\* \* @param UserRepository $userRepo \*/ public function \_\_construct(UserRepository $userRepo) { $this-\>userRepo = $userRepo; } /\*\* \* Display a listing of the resource. \*/ public function index() { $where = []; if (setting('pilots.hide\_inactive')) { $where['state'] = UserState::ACTIVE; } try { $users = $this-\>userRepo -\>with(['airline', 'current\_airport']) -\>orderBy('pilot\_id', 'desc') -\>findWhere($where); } catch (RepositoryException $e) { Log::emergency($e); } return view('staff::admin.index', ['users' =\> $users,]); }

Also, not sure what you plan on doing but I would usually keep any $request for its own method other than index unless there’s a reason to keep it in.

Thanks! Do you happen to know a good way to insert into the database? I’m lost after the form submits and does it’s checks… not sure where the actual insert sql command is! 🤪
 

Figured that out. But having an issue on finding where findWithoutFail functions are stored. 

1 hour ago, nickkecooper said:

Do you happen to know a good way to insert into the database?

I would get the form values from the submission using a Request (or App\Requests\Request…) $request, then I would validate it using $request->validate([…]) (although it might be done automatically), then call $this->REPO->create([..]) to insert it.

 

1 hour ago, nickkecooper said:

But having an issue on finding where findWithoutFail functions are stored. 

Not sure what you mean here, if it’s where the code actually is, it should be here

https://github.com/nabeelio/phpvms/blob/dev/app/Contracts/Repository.php#L19

Awesome thank you! Now how to fill in the input fields when you on an edit screen 🤨

20 minutes ago, nickkecooper said:

Now how to fill in the input fields when you on an edit screen 

As in filling the inputs in your form at URL.com/.../edit? You should be able to do something like this:

\<div class="form-group"\> {{ Form::label('FIELDNAME', 'FIELDNAME TEXT TO DISPLAY:') }}&nbsp;\<span class="required"\>\*\</span\> {{ Form::text('FIELDNAME', null, ['class' =\> 'form-control']) }} \<p class="text-danger"\>{{ $errors-\>first('FIELDNAME') }}\</p\> \</div\>

and it should auto-fill the values based on the model data (e.g. $users) you have, provided you have setup the Form::model().. binding before this. For more info, checkout how Nabeel does it in the admin area (airports for example), or view the Collective HTML docs here.

 

If you wanted to make it more traditional, you could also do something like this:

\<form action="{{ route('/users', $user-\>id) }}" method="post"\> @csrf @method('PUT') OR PATCH \<div class="form-group"\> \<label for="..."\>FIELDNAME TO DISPLAY\</label\> \<input type="text" name="FIELDNAME" id="..." class="form-control" value="{{ old('FIELDNAME', DEFAULT VALUE) }}" /\> OLD will display the last data the user has entered if it fails validation. @errors fields... \</div\> \</form\>

 

1 Like

Yea but it doesnt seem like the developer used the same format, and its driving me crazy how he got it to work lol 

 

The first solution you stated is the way he is doing it but I cant get it to work!

Really? I thought he was using the LaravelCollective HTML linked above?

Here’s his airports example.

1. https://github.com/nabeelio/phpvms/blob/dev/app/Http/Controllers/Admin/AirportController.php#L125 << Fetches the airport, sets the variable for use in the view and shows the view.

2. https://github.com/nabeelio/phpvms/blob/dev/resources/views/admin/airports/edit.blade.php#L6 << In the view, he defines the model binding (note the $airport) which should fill in the fields and match up the fieldname with the column name in the database.

3. https://github.com/nabeelio/phpvms/blob/dev/resources/views/admin/airports/fields.blade.php << His fields are defined here.

 

Does that help a bit more?

I edited my post you were right he uses it lol sorry its late! 

Ill take a closer look. I can’t use:

 {{ Form::model($airport, ['route' =\> ['admin.airports.update', $airport-\>id], 'method' =\> 'patch', 'id' =\> 'airportForm']) }}

In a module. When I replace the route it does not like the route. I’ve tried a ton of things to get it to work but can’t figure it out. 

Once I removed the ‘route’ line it worked like a charm! Not sure how to fix the routes not registering under a module but I’m sure it’ll come to me! 

What’s your routes that you have put in Routes/web.php (or AppServiceProvider)?

 

Edit: Just saw you posted at the same time haha. It could be related to the module issue on github, but what routes have you defined? Also, did it throw any errors or just a “Page Not Found”?

Under Modules/MyModule/Http/Routes/admin.php

 

 Route::post('staff/update{id}', 'AdminController@update');

 

The ‘method’ => ‘patch’, part of the Form::model(…) means you would have to declare it as a PATCH instead of a POST.

So does something like this work (obviously change airport to whatever you are using)?

 

Route::patch('staff/update/{id}', 'AdminController@update')-\>name('update');

{{ Form::model($airport, ['route' =\> ['YOURMODULEPREFIX.update', $airport-\>id], 'method' =\> 'patch', 'id' =\> 'airportForm']) }}

The name(‘update’) bit is what the route() uses to get the name, so by default it should be MODULENAME.update or (::) but it might not be working right now because of the issue.

 {{ Form::model($staff, ['route' =\> ['staff::admin.update', $staff-\>id], 'method' =\> 'patch', 'id' =\> 'staffForm']) }}

 

I made it this now. Still isn’t working, saying it is undefined. I also changed the admin.php line to show what you had put. Maybe it is an issue with the modules. 

 

15 minutes ago, nickkecooper said:

I made it this now. Still isn’t working, saying it is undefined

Hmm yeah it could be related. Although what you have there looks right to me.

You have to set a name for the route with ->name(“admin.update”); and then call it with “staff.admin.update”. If you look at the installer module you’ll see it. I thought it defined route names automatically but only for resources

1 Like

Fixed! Thank you  Now when I do it the correct way on the create.blade.php, I get this error Column not found: 1054 Unknown column ‘_token’. Should I do an except command on my insert? 

No, the _token is the CSRF token so that’s not stored in the database at all. Just realised that the CSRF token has been disabled (not sure why), so if you have anything to do with @csrf or _token in your form just remove it for now.

That token is put there automatically by the Form::Open