I've a problem, I'm trying test my aplicattion with PHPUnit, in that aplicattion I've multiple forms where the user can upload files, and since Admin can upload differents files, I'm trying test a form where the admin can upload an image, and an audio, but I don't get it; here's my code:
public function testCreateAudiobooks()
{
Storage::fake('uploads/audiobooks/cover_pages');
Session::start();
$response = $this->json('POST', 'admin-audiobooks', [
'audiobook_title' => 'Audiolibro con Unit',
'audiobook_description' => 'Descripción de audiolibro desde Unit',
'audiobook_author' => 'PHPUnit',
'audiobook_section' => 'Pruebas',
'audiobook_keywords' => 'Unit',
'audiobook_storyteller' => 'Luis',
'audiobook_duration' => '15',
'audiobook_visibility' => 'Visible',
'audiobook_cover_page' => UploadedFile::fake()->image('45.png'),
'audiobook_location' => UploadedFile::fake(),
'_token' => csrf_token()
]);
Storage::disk('uploads/audiobooks/cover_pages')->assertMissing('45.png');
$response->assertRedirect();
}
As you can see, I pass the UploadedFile in audiobook_cover_page, but I dunno how can pass something similar for the audiobook_location
I found this artcile, and I try do something similar, but still didn't
If someone can help me, I'll be really gratefull!
Related
I'm loading multiple images and sometimes it works fine and another hangs, other times it doesn't take certain images and redirects me to page 404. I would like if you can give me a hand. I appreciate very much any intention.
I am using Livewire as follows:
<input wire:model="imagenes" type="file" name="imagenes" class="form-control-file" multiple>
Once the images are selected, it goes through the validator:
$this->validate([
'imagenes.*' => 'image|max:2048',
]);
And to save the images I am using the following methodology
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
}
On the filesystem:
'imagenesPropiedades' => [
'driver' => 'local',
'root' => public_path(),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
I get this error in console
Can you give me a suggestion to improve this load please.
The problem was that since I use livewire in real time, I had not contemplated the enctype = "multipart / form-data" tag, and I also had to expand the max_upload server spaces. Thanks a lot
I've been trying to work with Guzzle and learn my way around it, but I'm a bit confused about using a request in conjunction with empty or null values.
For example:
$response = $client->request('POST',
'https://www.testsite.com/coep/public/api/donations', [
'form_params' => [
'client' => [
'web_id' => NULL,
'name' => 'Test Name',
'address1' => '123 E 45th Avenue',
'address2' => 'Ste. 1',
'city' => 'Nowhere',
'state' => 'CO',
'zip' => '80002'
],
'contact' => [],
'donation' => [
'status_id' => 1,
'amount' => $donation->amount,
'balance' => $donation->balance,
'date' => $donation->date,
'group_id' => $group->id,
],
]
]);
After running a test, I found out that 'web_id' completely disappears from my request if set to NULL. My question is how do I ensure that it is kept around on the request to work with my conditionals?
At this point, if I dd the $request->client, all I get back is everything but the web_id. Thanks!
I ran into this issue yesterday and your question is very well ranked on Google. Shame that it has no answer.
The problem here is that form_params uses http_build_query() under the hood and as stated in this user contributed note, null params are not present in the function's output.
I suggest that you pass this information via a JSON body (by using json as key instead of form_params) or via multipart (by using multipart instead of form_params).
Note: those 2 keys are available as constants, respectively GuzzleHttp\RequestOptions::JSON and GuzzleHttp\RequestOptions::MULTIPART
Try to define anything like form_params, headers or base_uri before creating a client, so:
// set options, data, params BEFORE...
$settings = [
'base_uri' => 'api.test',
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'ajustneedatokenheredontworry'
],
'form_params' => [
'cash' => $request->cash,
'reason' => 'I have a good soul'
]
];
// ...THEN create your client,
$client = new GuzzleClient($settings);
// ...and finally check your response.
$response = $client->request('POST', 'donations');
If you check $request->all() at the controller function that you are calling, you should see that were sent successfully.
For those using laravel, use this:
Http::asJson()
In my CakePHP application, I have applied Url validations so that admin can access only those actions which are defined for admin and same as with users.
In my application, "surveylist" is the action of admin and when any user directly access that action(surveylist), URL validations work(Unauthorized access msg is displayed).
But below that message ctp file of surveylist executes forcefully and show errors because I have validated URL through the try-catch block and it cannot get the set variables of action.
I want that ctp file should not execute if unauthorize error comes.
My code for surveylist is:-
public function surveylist($pg=null){
try{
if($this->checkPageAccess($this->params['controller'] . '/' . $this->params['action'])){
$this->Paginator->settings = array(
'Survey' => array(
'limit' => 5,
'order' => 'created desc',
'conditions'=>array('is_deleted'=> 0),
'page' => $pg
)
);
$numbers = $this->Paginator->paginate('Survey');
$this->set(compact('numbers'));
}else{
$this->Flash->set(__('Unauthorised access'));
}
}catch(Exception $e){
$this->Flash->set(__($e->getMessage()));
}
}
I don't want the ctp file of surveylist to execute if control comes to else.
Plz, help me out......
Thanx in advance...
I suppose you are using prefix to separate admin and users, if not please do that it is great way to handle and restrict methods.
After doing that you have to make condition to check which prefix(admin, user) is currently active and according that load Auth component and allow action in allow() method of Auth.
Example:
$this->loadComponent('Auth',[
/*'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],*/
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => false
],
'authError' => 'You are not authorized to access that location.',
]);
if ($this->request->params['prefix']=='admin') {
// Put actions you want to access to admin in allow method's array
$this->Auth->allow(array('add', 'edit', etc...));
} else if ($this->request->params['prefix']=='user') {
// Put actions you want to access to user in allow method's array
$this->Auth->allow(array('login', 'view', etc...));
}
This way you can restrict actions for particular role.
Hope this helps!
Ok, this might have a very simple answer but for the life of me my I can not seem to find an answer! I am signing up users from a text into a lights out box (SimpleModal) which AJAX loads a new page for an admin to sign up a user to a selected client list.
This all works without any issues at all, so long as the model checks are correct. I have two checks, one makes sure the username is unique and that the password has at lest 8 characters, code below. But when one or both of these checks are not meet, then the user is taken to the AJAX URL and the 'message' is then displayed. This is not what I need I need it to be taken back to the lights out box or set these messages as flash error message to be printed on to the screen.
Or should I remove these checks from the modal and get JQuery to check them instead?
Any ideas?
All help very welcome.....
Model Code ::
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('isUnique'),
'message' => 'Sorry but a unique username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'Sorry but a password of 8 characters or more is required'
)
) ... more check follow but these are the issues....
CTP file ::
$this->layout = 'ajax';
$AddUserForm = $this->Form->create('User', array('url' => '/ADD-USER-URL-HERE'));
$AddUserForm .= $this->Form->input('username');
$AddUserForm .= $this->Form->input('password');
$AddUserForm .= $this->Form->input('role', array('options' => array('admin' => 'Admin', 'user' => 'User')));
$AddUserForm .= $this->Form->input('data_id', array('options' => array($data), 'empty'=>true));
$AddUserForm .= $this->Form->end(__('SAVE NEW USER'));
echo $AddUserForm;
In your ctp file
$('form').on('submit', function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(res) {
$('form').replaceWith(res);
})
})
can be used for validating the data using the above script,
I think this will help you for submitting the form via ajax and you can also display the error messages using the response coming from the ajax.
Hope this will help you.
I'm building a user panel, and having some problems with data validation. As an example, the page where you change your password (custom validation rule comparing string from two fields (password, confirm password)):
Route:
Router::connect('/profile/password', array('controller' => 'users', 'action' => 'profile_password'));
Controller:
function profile_password()
{
$this->User->setValidation('password'); // using the Multivalidatable behaviour
$this->User->id = $this->Session->read('Auth.User.id');
if (empty($this->data))
{
$this->data = $this->User->read();
} else {
$this->data['User']['password'] = $this->Auth->password($this->data['User']['password_change']);
if ($this->User->save($this->data))
{
$this->Session->setFlash('Edytowano hasło.', 'default', array('class' => 'success'));
$this->redirect(array('action' => 'profile'));
}
}
}
The problem is, that when I get to http://website.com/profile/password and mistype in one of the fields, the script goes back to http://website.com/users/profile_password/5 (5 being current logged users' id). When I type it correctly then it works, but I don't really want the address to change.
It seems that routes aren't supported by validation... (?) I'm using Cake 1.3 by the way.
Any help would be appreciated,
Paul
EDIT 1:
Changing the view from:
echo $form->create(
'User',
array(
'url' => array('controller' => 'users', 'action' => 'profile_password'),
'inputDefaults' => array('autocomplete' => 'off')
)
);
to:
echo $form->create(
'User',
array(
'url' => '/profile/password',
'inputDefaults' => array('autocomplete' => 'off')
)
);
does seem to do the trick, but that's not ideal.
Check the URL of the form in the profile_password.ctp view file.
Try the following code:
echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'profile_password')));
Also, I think your form might be a little vulnerable. Try using Firebug or something similar to POST a data[User][id] to your action. If I'm right, you should be setting:
$this->data['User']['id'] = $this->Auth->user('id');
instead of:
$this->User->id = $this->Session->read('Auth.User.id');
because your id field is set in $this->data.
HTH.