testing that a user can edit profile - laravel

Simple enough situation, a user can edit their own profile. Run it through a browser test, works like a charm. Make a test for it... well now we have something interesting. I posted this over on the Laracasts site, but I figure more exposure is always good.
/** #test */
function auth_user_can_edit_own_profile()
{
$user = factory('App\User')->create();
$user->setProfile(); //this just makes an empty profile so a 1-1 relation exists
$this->actingAs($user);
$response = $this->post('profile/'.$user->id.'/update',[
'quote'=>'Hello World',
]);
$response->assertSee('Hello World');
}
I get a failure. what displays on the screen is a redirect to the main page. O.o Nothing in my code should make that happen.
I believe it has something to do with my form request's authorize() method. However, I fail to see how. I have tried using $this->withoutExceptionHandling() in my test with no change.
storeProfile form request:
public function authorize()
{
$profile = $this->route('profile');
if ($this->user()->can('edit profile') || $this->user()->id == $profile->user_id)
{
return true;
}
return false;
}
Profile Controller update:
public function update(storeProfile $request, Profile $profile)
{
$profile->update($request->except('name'));
$profile->save();
if($profile->user->name != $request->input('name'))
{
$profile->user()->update(['name' => $request->input('name')]);
//TODO event to track name changes
}
return redirect()->action('ProfileController#show',['id' => $profile->user_id]);
}
Any insights to this would be really helpful, but I truly don't understand what is happening. Thank you all for taking the time to read and help!
Things I have tried:
Set authroize to return true. - no change
$this->flushSession(); - no change
$this->withoutExceptionHandling() - nochange

Related

Define fields based on resource's model attributes in Laravel Nova

I have a (relatively) basic need in Nova that I can't seem to figure out and I slowly start to feel that I'm approaching things the wrong way.
So, I've got a User, Company, Device and Transfer models and respectively resources, everything pretty default regarding the resource setup.
The schema is the following:
users: id, company_id
companies: id, type_id, name where type_id is pointing to one of three pre-populated types (manufacturer, dealer, client)
devices: id, imei
transfers: id, from_company_id, to_company_id, accepted_at
and Transfer is in a Many-to-Many with Device.
The idea behind the transfers being that Manufacturers transfer to Dealers, Dealers transfer to Clients, so it's really only a one-way thing.
Now the problem occurs at the following crucial point in the logic:
In my Transfer resource pages, I want to show different fields depending on the type of the company the currently authenticated user belongs to. Basically, if the company is:
Manufacturer, then display a DEALER column populated with the transfers' toCompany relation;
Dealer, then display a CONTRAGENT column populated with the transfers' fromCompany or toCompany relations (depending on which mathces the current auth() company)
Client, then display a DEALER column populated with the transfers' fromCompany
All of the described logic works fine with the following code (App\Nova\Transfer.php as is) UNTIL I wanted to finally display the transfer's devices on the details page:
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Http\Requests\NovaRequest;
class Transfer extends Resource
{
public static $model = \App\Models\Transfer::class;
public static $title = 'id';
public static $search = [
'id',
];
public static $with = [
'fromCompany',
'toCompany'
];
public function fields(Request $request)
{
$company = auth()->company();
if($company->hasType('manufacturer'))
{
$contragentTitle = 'Dealer';
$contragent = 'toCompany';
}
else if($company->hasType('dealer'))
{
//\Debugbar::info($this); //showing empty resource when populating the devices
$contragentTitle = 'Contragent';
$contragent = $this->fromCompany->is($company) ? 'toCompany' : 'fromCompany'; //exception here, since the resource is empty and fromCompany is null
}
else
{
$contragentTitle = 'Dealer';
$contragent = 'fromCompany';
}
$contragentCompanyField = BelongsTo::make("$contragentTitle company", $contragent, Company::class);
if($company->hasType('dealer'))
{
$contragentCompanyField->displayUsing(function ($contragentCompany) use ($contragent){
return $contragentCompany->title() . " (".($contragent == 'toCompany' ? 'Outgoing' : "Incoming").')';
});
}
return [
ID::make(__('ID'), 'id')->sortable(),
$contragentCompanyField,
BelongsToMany::make('Devices') //problematic field, when removed, everything is fine...
];
}
public static function indexQuery(NovaRequest $request, $query)
{
if(auth()->check())
{
return $query->where(function($subQuery){
return $subQuery->where('from_company_id', auth()->company()->id)->orWhere('to_company_id', auth()->company()->id);
});
}
}
public function cards(Request $request)
{
return [];
}
public function filters(Request $request)
{
return [];
}
public function lenses(Request $request)
{
return [];
}
//action is working fine (additional canRun added to avoid policy conflicts)
public function actions(Request $request)
{
return [
(new Actions\AcceptTransfer())->showOnTableRow()->canSee(function ($request) {
if ($request instanceof \Laravel\Nova\Http\Requests\ActionRequest) {
return true;
}
return $this->resource->exists
&& $this->resource->toCompany->is(auth()->company())
&& $this->resource->accepted_at === null;
})->canRun(function ($request) {
return true;
})
];
}
}
Now the strange thing that is happening is that the fields() method gets called multiple times on multiple ajax requests behind the scenes with Nova and when populating the devices relationship table, it gets called without a resource, although a call is never actually needed (as far as I can grasp the mechanics behind Nova) or at least when fetching relationships, you must still have the model information (at least the ID) somewhere to fetch by... So basically, if I'm a user of a dealer company, I can't see the devices that are being transferred (currently throwing a calling is() on null exception).
Now, this happens to be a big problem, since it hinders most of the stuff I need for my transfers, but also generally I don't like my approach so far, so... What would be the right way to achieve this multi-layer resource? Ideally I'd like to define three different transfer resource classes and somehow tell nova which one to use based on the user's company's type (since branching will most probably just grow more complex and therefore uglier as of the current aproach), but I can't figure out the way to do so.
I've also considered moving this entire logic to a separate Nova tool, but I really don't know much about them yet and whether that would be the right option... The only thing stopping me is that I still won't be able to elegantly solve the multi-layer problem and will have to write much of the otherwise useful Nova CRUD logic and views myself...
Any explanations (regarding the multiple calls of fields() and why resource is empty) or general structural recommendations to solve this case would be greatly appreciated! Many thanks in advance!
EDIT:
I was able to circumvent the error by taking advantage of viaResourceId, so instaed of $this I ended up using:
$transfer = $this->id ? $this->resource : \App\Models\Transfer::find($request->viaResourceId);
but the messy code and the unneeded calls still remain an open question. Thanks again in advance!
Here is an example of how I handled this:
public function fields(NovaRequest $request)
{
/** #var \App\Models\User $user */
$user = $this->id ? $this->resource : \App\Models\User::find($request->viaResourceId);
if ($user && $user->whatEver()) {
// display special fields in preview/detail view
return [...];
}
// display for index and if no model is found
return [...];
}

Laravel Nova - Observer Update Method Causes 502

When trying to update a resource in Laravel Nova that has a Observer the update loads for a while and then ends with a 502 error. The observer is registered correctly (the created method works fine) and I'm not trying to do anything special in the updated method. Any ideas?
public function updated(Model $model)
{
//
$model->title = 'test';
$model->save();
}
If I try this without the $model->save(), there is no 502 error but the change I want to happen also doesn't happen. I get the green success message, and any change I make on the form prior to updating occurs, but not the change I'm trying to make during the updated method.
Any help troubleshooting this would be appreciated
I am not very good at Laravel, but I think, that you should to try this:
In your model file add method:
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
Then, in your updated method in observer do something like this:
public function updated(Model $model)
{
$model->title = 'test';
$model->saveQuietly();
}

October CMS - Extending the function of a plugin?

I've created a plugin to extend the User plugin and I now want to extend the update function of its controller.
Actually what I'd like to do is to check some data when an admin
clicks on the Update button then, according to the data, let the admin edit the user form as usual or redirect him to the user list.
I'm trying to do this through a route in my plugin:
Route::get('backend/rainlab/user/users/update/{id}', '\RainLab\User\Controllers\Users#check_update');
in my Plugin.php file
public function boot()
{
\RainLab\User\Controllers\Users::extend( function($controller) {
$controller->addDynamicMethod('check_update', function($recordId = null, $context = null) use ($controller) {
return $controller->asExtension('FormController')->update($recordId, $context);
});
});
}
But I get a blank page. The user form is not displayed.
Can someone helps me ?
This wont work as it will break life-cycle of back-end and direct call method of controller.
As other solution, we can use events :) - backend.page.beforeDisplay
In your plugin's plugin.php file's boot method
public function boot() {
\Event::listen('backend.page.beforeDisplay', function($controller, $action, $params) {
if($controller instanceof \RainLab\User\Controllers\Users) {
// for update action
if($action === 'update') {
// check data ($params) and make decision based on that
// allow user to edit or NOT
if(true) {
// just redirect him to somewhere else
\Flash::error('Please No.');
return \Redirect::to('/backend/rainlab/user/users');
}
// if all good don't return anything and it will work as normal
}
}
});
}
it will do the job based on condition you can allow user to edit OR not (redirect him with message to other action).
if any doubts please comment.

Laravel Backpack - getting current record from crud controller

In my crud controller I am trying to get the name of the person who is currently being edited.
so
http://192.168.10.10/admin/people/93/edit
In the people crud controller
public function setup() {
dd(\App\Models\People::get()->first()->name)
}
This returns the first person not the person currently being edited.
How do I return the current person (with an id of 93 in this example)
Ok, So since you use backpack look into CrudController to see how the method looks:
public function edit($id)
{
$this->crud->hasAccessOrFail('update');
$this->data['entry'] = $this->crud->getEntry($id);
$this->data['crud'] = $this->crud;
$this->data['fields'] = $this->crud->getUpdateFields($id);
$this->data['id'] = $id;
return view('crud::edit', $this->data);
}
So now you can overwrite the edit function and change whatever you want. You can even create a custom edit page if you so wish.
Setup on the other hand is usually used to add things like
$this->crud->addClause(...);
Or you can even get the entire constructor and put it in the setup method because setup call looks like this:
public function __construct()
{
// call the setup function inside this closure to also have the request there
// this way, developers can use things stored in session (auth variables, etc)
$this->middleware(function ($request, $next) {
$this->setup();
return $next($request);
});
}
So you could do something like \Auth::user()->id;
Also it's normal to work like this. If you only use pure laravel you will only have access to the current id in the routes that you set accordingly.
Rahman said about find($id) method. If you want to abort 404 exception just use method findOrFail($id). In my opinion it's better way, because find($id)->name can throw
"Trying to get property of non-object error ..."
findOrFail($id) first fetch user with specified ID. If doesn't exists just throw 404, not 500.
The best answer is:
public function edit($id)
{
return \App\Models\People::findOrFail($id);
}
Good luck.
you need person against id, try below
public function setup($id) {
dd(\App\Models\People::find($id)->name);
}

Laravel 4 testing session in controllers

I have a problem with testing controllers in Laravel 4.
I have the next code:
public function getRemind()
{
$status = \Session::get('status');
$error = \Session::get('error');
$email = \Session::get('email');
return \View::make('admin/reminds/remind_form', compact('status', 'error', 'email'));
}
And I want to test if correct data passed in views by controller:
public function testGetRemind()
{
\Session::set('status', 'status');
\Session::set('error', 'error');
\Session::set('email', 'email');
$response = $this->action('GET', 'Admin\RemindersController#getRemind');
$this->assertTrue($response->isOk(), 'Get remind action is not ok');
$this->assertViewHas('status', 'status');
$this->assertViewHas('error', 'error');
$this->assertViewHas('email', 'email');
}
But this doesn't work.
Also I can't mock Session-class, because it not allowed by framework - there are a lot of errors when I try doing it.
Call Session::start() at the start of your test. When you call an URL in a test, the session is started if it has not already been started, wiping any existing data put into it.
Since v4.1.23, you can also do $this->session($arrayOfSessionData), which handles the starting of the session for you.

Resources