I'm trying to send notifications via PushBullet to my mobile phone using the lahaxearnaud/laravel-pushbullet plugin. Only one problem, I installed it correctly and I'm still getting this error: Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, boolean given, called in vendor\guzzlehttp\guzzle\src\Client.php on line 87 and defined.
This is my code:
<?php
namespace RPR\Http\Controllers;
use DB;
use Auth;
use Redirect;
use Session;
use Mail;
use Validator;
use Carbon\Carbon;
use Illuminate\Http\Request;
use PushBullet;
use RPR\User;
use RPR\News;
use RPR\Sponsors;
use RPR\Partners;
use RPR\Events;
use RPR\Http\Controllers\Controller;
class SiteController extends Controller
{
/**
* PostContact
*
* #return Response
*/
public function PostContact(Request $request)
{
$messages = [
'name.required' => 'U moet een naam opgeven.',
'name.min' => 'Uw naam moet minstens :min tekens bevatten.',
'email.required' => 'U moet een e-mail adres opgeven.',
'email.min' => 'Uw e-mail adres moet minstens :min tekens bevatten.',
'email.email' => 'Uw e-mail adres moet geldig zijn.',
'subject.required' => 'U moet een onderwerp opgeven.',
'subject.min' => 'Uw onderwerp moet minstens :min tekens bevatten.',
'message.required' => 'U moet een bericht opgeven.',
'message.min' => 'Uw bericht moet minstens :min tekens bevatten.'
];
$rules = [
'name' => 'required|min:3',
'email' => 'required|min:3|email',
'subject' => 'required|min:3',
'message' => 'required|min:3'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
DB::table('contact')->insert([
'name' => $request->get('name'),
'email' => $request->get('email'),
'subject' => $request->get('subject'),
'message' => $request->get('message'),
'ip' => $request->ip(),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
PushBullet::all()->note('Belangrijk', 'Er is een nieuw contact bericht.');
$request->session()->flash('alert-success', 'Uw bericht is succesvol verzonden!');
return Redirect::back();
}
}
The main issue is the PushBullet::all()->note('Belangrijk', 'Er is een nieuw contact bericht.'); wich does the request. After That is fired, I got the issue. Anyone an idea?
Kindest regards,
Robin
Related
In my HunterModel.php file all the validations and custom messages are from the validations, but I don't know if my form_create.php doesn't show the error messages, they simply return to the form without shows the failures committed by the user, why is this happening?
form_create.php
<?php if (isset($validation)) : ?>
<div class="text-danger">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>
<form action="<?= site_url('create')?>" method="POST">
...
</form>
In my HunterController.php method createHunter() must do the record insertion operation, checking if everything is right or returns to the form showing the necessary corrections to the user.
HunterController.php
public function createHunter()
{
try {
helper(['form']);
$hunter = new HunterModel();
$data = [
'name_hunter' => $this->request->getPost('name_hunter'),
'age_hunter' => $this->request->getPost('age_hunter'),
'height_hunter' => $this->request->getPost('height_hunter'),
'weight_hunter' => $this->request->getPost('weight_hunter'),
'type_hunter' => $this->request->getPost('type_hunter'),
'type_nen' => $this->request->getPost('type_nen'),
'type_blood' => $this->request->getPost('type_blood')
];
if ($hunter->insert($data)){
return $this->response->redirect(site_url('listing'));
} else {
$data['validation'] = $this->validator;
echo view('form_create', $data);
}
} catch (\Exception $e) {
exit($e->getMessage());
}
}
HunterModel.php
// Validation
protected $validationRules = [
'nome_hunter' => 'required|max_length[30]',
'idade_hunter' => 'required|integer',
'altura_hunter' => 'required|decimal',
'peso_hunter' => 'required|decimal',
'tipo_hunter' => 'required|max_length[30]',
'tipo_nen' => 'required|max_length[30]',
'tipo_sanguineo' => 'required|max_length[3]'
];
protected $validationMessages = [
'nome_hunter' => [
'required' => 'O nome do Hunter não pode ficar vazio.',
'max_length' => 'O nome do Hunter precisa ter no máximo 30 caracteres.'
],
'idade_hunter' => [
'required' => 'A idade do Hunter não pode ficar vazia.',
'integer' => 'A idade do Hunter precisa ser um número inteiro.'
],
'peso_hunter' => [
'required' => 'O peso do Hunter não pode ficar vazio.',
'decimal' => 'O peso do Hunter precisa ser um número decimal.'
],
'altura_hunter' => [
'required' => 'A altura do Hunter não pode ficar vazia.',
'decimal' => 'A altura do Hunter precisa ser um número decimal.'
],
'tipo_hunter' => [
'required' => 'É necessário definir o tipo de Hunter.',
'max_length' => 'O tipo de Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_nen' => [
'required' => 'É necessário definir o nen do Hunter.',
'max_length' => 'O nen do Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_sanguineo' => [
'required' => 'É necessário definir o tipo sanguíneo do Hunter.',
'max_length' => 'O tipo sanguíneo do Hunter precisa ter no máximo 3 caracteres.'
]
];
you should learning again about validate data,
learn this page
https://codeigniter4.github.io/userguide/libraries/validation.html#form-validation-tutorial
if you want to use helper function, try this
function yourController($request){
helper(['form']);
$validation = \Config\Services::validation();
$rules = [
"nome_hunter" => [
"label" => "nome_hunter",
"rules" => 'required|max_length[30]',
]
];
if ($this->validate($rules)) {
$hunter = new HunterModel();
$hunter->insert($data)
$session = session();
$session->setFlashData("success", "Successful");
return redirect()->to('/');
} else {
$data["validation"] = $validation->getErrors();
}
}
or you can make the validation on your controller, don't make it on model
you can try this too
how to validate form data in codeigniter 4
I'm using Respect to validate some forms in a project but this project is in Spanish and I don't understand how messages work after spending a long time reading the documentation and even its code.
I'm using Slim and I'm using a NestedValidationException following an example I read on a tutorial on Youtube.
This is the validate method:
public function validate($request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
//In English it's enough with
//$this->errors[$field] = $e->getMessages();
$this->$errors[$field] = $e->getMainMessage();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
I've seen some responses before but some are very hard to grasp for me as I don't intend on doing a whole translation of the library. I'm just attempting to write 5 or 6 custom messages.
EDIT: A method using the messages:
$validation = $this->c->validator->validate($request, [
'username' => v::noWhitespace()->notEmpty()->usernameAvailable(),
'email' => v::noWhitespace()->notEmpty()->email()->emailAvailable(),
'password1' => v::noWhitespace()->notEmpty(),
'password2' => v::noWhitespace()->notEmpty()->identical($inputPassword),
]);
Using findMessages with the parameter you're translating the messages. You just have to replace the content in the catch block:
catch (NestedValidationException $e) {
$errors = $e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
$filteredErrors = array_filter($errors); // Ensure the array is not containing empty values
$this->$errors[$field] = $filteredErrors;
}
I'm trying to include the class that treats the Request from my form, but it always returns error from not found, however, I've already checked and reverted and the file and patch are correct.
I already tried to update the composer to see if it solved, but without success, follow the code below.
Arguments "Class App\Http\Requests\CadastroRequest does not exist"
File CadastroController.php
<?
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB; // Banco de dados
use Request; // Tratamento URI
use Validator; // Validação
use App\Cadastro; // Modelo
use App\Http\Requests\CadastroRequest; // Regras do formulário
class CadastroController extends Controller {
// Formulário de Cadastro
public function cadastro(){
return view('cadastro.formulario');
}
// Registrar Usuário
public function salvar( CadastroRequest $request ){
Cadastro::create( $request->all() );
return redirect('/cadastro/obrigado')->withInput();
}
}
?>
File CadastroRequest.php (root/app/Http/Requests/CadastroRequest.php)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CadastroRequest extends FormRequest {
public function authorize() {
return true; // Manter true para teste
}
public function rules() {
return [
# Informações de contato
'nome' => 'required|min:10',
'email' => 'required|min:10',
'celular' => 'min:11|max:15',
# Informações de acesso
'senha' => 'required|numeric|min:3|max:8',
'rsenha' => 'required|numeric|min:3|max:8',
# Informações de endereço
'estado' => 'required|min:10',
'cidade' => 'required|min:10',
'cep' => 'required|min:10',
'endereco' => 'required|min:10',
'numero' => 'required|min:10',
'bairro' => 'required|min:10',
];
}
public function messages(){
return [
'nome.required' => 'Você precisa informar seu nome.'
'email.required' => 'Insira um e-mail valido, você precisa confirmar o registro.'
'senha.required' => 'Senha é obrigatória.'
'rsenha.required' => 'Confirmação da senha é obrigatória.'
'estado.required' => 'Saber seu estado ajuda a lhe informar jogos acontecendo no seu estado.'
'cidade.required' => 'Saber a cidade que mora ajuda a lhe informar os jogos próximos a você.'
'cep.required' => 'Campo CEP é obrigatório.'
'endereco.required' => 'Campo Endereço é obrigatório.'
'numero.required' => 'Campo Número é obrigatório.'
'bairro.required' => 'Campo Bairro é obrigatório.'
];
}
}
Run this in your terminal :
composer dump-autoload
it will add your class to your project
If it not work, try to add the new request via artisan :
php artisan make:request CadastroRequest
then just copy and paste your code
I'm trying to generate an get unique slugs, just like MyBB does, but it doens't work well...
I'm using the plugin https://github.com/cviebrock/eloquent-sluggable/tree/2.x for Laravel 4.2.
So I got this:
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class ForumController extends \BaseController implements SluggableInterface {
use SluggableTrait;
protected $sluggable = [
'build_from' => 'title',
'save_to' => 'slug',
];
And in that Class, I don't know how I need to generate the slug,
it needs to be generated in this function:
public function PostTopic($cid)
{
//Get all the data and store it inside Store Variable
$data = Input::all();
// Make's messages of faults
$messages = array(
'title.required' => 'U moet een titel opgeven!',
'titel.unique' => 'De opgegeven titel bestaat al, gebruik een andere.',
'message.required' => 'u moet een bericht opgeven!',
'spamprt' => 'honeypot', //spam protection
'time' => 'required|honeytime:60'
);
$rules = array(
'title' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules, $messages);
//process the storage
if ($validator->fails())
{
return Redirect::back()->with('errors', $validator->errors())->withInput();
}else{
//store
$thread = new Thread;
$thread->cid = $cid;
$thread->title = Input::get('title');
$thread->message = Input::get('message');
$thread->prefix = 0;
$thread->uid = Auth::id();
$thread->username = Auth::user()->username;
$thread->date_posted = Carbon\Carbon::now();
$thread->save();
Session::put('_token', sha1(microtime()));
//redirect
return Redirect::back()->with('message', 'Uw bericht is succesvol geplaatst!');
}
}
But how? And how do I need to get the slugs to display them in an URL or so?
I have a problem in my site created with cakePhp 2.x, when I try to register an account my form check all my rules of my fields and beforeSave crypt the password, but crypt the password before check the password(MatchPassword) with the confirm password and then return me the error tha the two password is't equal because the password is crypt with 40characters.
Here is my Model code, How can I solv this problem?
<?php
//questo modello interessa lòa tabella User
class User extends AppModel{
public $name = 'User'; //non utilizzata nel sito è il nome del modello alla fine per migliorare la compatibilità
public $validate = array(
'password' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
),
'min_lunghezza' => array(
'rule' => array('minLength',5),
'message' => 'La password deve contenere almeno 5 caratteri'
),
'max_lunghezza' => array(
'rule' => array('maxLength',15),
'message' => 'La password deve contenere al massimo 15 caratteri'
),
'password_uguale' => array(
'rule' => 'matchPasswords',
'message' => 'Not equal password'
)
),
'password_confirm' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
)
)
);
public function matchPasswords($data){
if ($data['password']==$this->data['User']['password_confirm']){
return true;
}
$this->invalidate('password_confirm','Le due password non coincidono');
return false;
}
public function beforeSave(){
//crypt
if (isset($this->data['User']['password'])){
$this->data['User']['password']=AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
I had a similar problem -- I'm not sure if it's exactly what you were asking -- but I needed to validate my model, before the beforeSave() rules were applied.
I found CakePHP's Validating Data from the Controller page helpful. Basically, you set the data
$this->ModelName->set($this->request->data);
Then you can check the model's validates() method...
if ($this->ModelName->validates()) { // ...
Then, you can decide whether to save the model or show the user an error using, e.g., $this->Session->setFlash().