Validating JSON input Laravel - json

I am using laravel , and json input from the client. I would like to know if there is a way to create a form request that does json validation instead of url parameters. I found this class online :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class JsonRequest extends FormRequest {
/**
* Get the validator instance for the request.
*
* #return \Illuminate\Validation\Validator
*/
protected function getValidatorInstance()
{
$factory = $this->container->make('Illuminate\Validation\Factory');
if (method_exists($this, 'validator'))
{
return $this->container->call([$this, 'validator'], compact('factory'));
}
return $factory->make(
$this->json()->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes()
);
}
}
Now , when I make a class that extends this instead of Request, I am able to validate. This is an example:
<?php
namespace App\Http\Requests;
use App\Http\Middleware\AuthTokenMiddleware;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Input;
class VotesCreateRequest extends JsonRequest
{
public function response(array $errors)
{
//
return response()->json(["error_list" => $errors], 200);
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{return true;
if(AuthTokenMiddleware::getUser()->can('access-group',Input::get("grp_id"))){
return true;
}
else{
return false;
}
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'sub_items'=>'required|array',
'sub_items.*.email' =>'required'
];
}
}
But I want to know how to validate items inside items of the json file .
For example, i have :
{"sub_items":["something","another thing","yet another","another ","last"]}
How do I validate if all these items in sub sub_items are of type email ?

Related

Laravel ajax response issue returning with html content

I am using ajax for ratings. Rating successfully but return response with html code above the json. And it is because of send mail function.
The this code alwasy attached when return response and may be it was from send mail function.
When I am removing Mail function it will return proper result and its working well.
If i were in your place i will work with jobs.
So Here is how it goes
php artisan make:job SendingEmail
App\Jobs\SendingEmail.php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
class SendingEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $admin_email;
protected $email_data;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($admin_email,$email_data)
{
$this->email_data = $email_data;
$this->admin_email = $admin_email;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Mail::to($this->admins_email)->send(new RateNotification($this->email_data));
}
}
App\Jobs\SendingEmail::dispatch($podcast);
In Your Controller add this
App\Jobs\SendingEmail::dispatch($admin_email,$email_data);

Create multiple files to differentiate routes in laravel 5.4

This is my RouteServiceProvider that I have changed for creating multiple routes files.
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
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';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot(Router $router) {
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* #return void
*/
public function map(Router $router) {
$this->mapApiRoutes($router);
$this->mapWebRoutes($router);
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes($router) {
$router->group(['namespace' => $this->namespace, 'middleware' => 'web'], function ($router) {
foreach (glob(app_path('Http/Routes/Web/*.php')) as $eachRoute) {
require $eachRoute;
}
});
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* #return void
*/
protected function mapApiRoutes($router) {
$router->group(['prefix' => 'api', 'namespace' => $this->namespace, 'middleware' => 'api'], function ($router) {
foreach (glob(app_path('Http/Routes/Api/*.php')) as $eachRoute) {
require $eachRoute;
}
});
}
}
Open your RouteServiceProvider
use Illuminate\Routing\Router; statement top of the file.
/**
* Define the routes for the application.
*
* #return void
*/
public function map(Router $router) {
$this->mapApiRoutes();
$this->mapWebRoutes($router);
//used Router object above in map function
}
This is only for web routes, You can also create for api , you need to create directory to distinguish it.
and finally :
protected function mapWebRoutes($router) {
$router->group(['namespace' => $this->namespace], function ($router) {
foreach (glob(base_path('routes/web/*.php')) as $eachRoute) {
require $eachRoute;
}
});
}

Having a challenge with Laravel 5.4 requests namespace

I'm trying to reference the Requests class in Laravel, I've tried so many fixes with the keyword "use" but each time I keep getting Reflection exception
that says app\path\specified doesn't exist. I'm confused.
Here is my code:`
<?php
namespace App\Http\Controllers;
//namespace App\Http\Request;
//use Illuminate\Http\Requests;
//use app\Http\Requests\ContactFormRequest;
use App\Message;
use App\Mail\SendMessage;
use Session;
//use App\Requests;
class AboutController extends Controller
{
public function create()
{
return view ('about.contact');
}
public function store(App\Requests\SendMessageRequest $request)
{
$message = $request->message;
Mail::to('myemail')
->send(new SendMessage($message, $request->email,$request->name));
THE REQUESTS CLASS
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required',
'email' => 'required|email',
"message" => 'required',
];
}
}
The commented line(//) are what I've tried
SendMessageRequest is the name of my Request class.
Sorry, I canĀ“t comment your post. However can you also send the SendMessageRequest Class? Is that a subclass of the Request in Laravel?

How to login from different tables in Yii2 basic application?

i have two table : Admin and Employees.
with different columns name.
how to create database login system for this scenario.
i am using Yii2 basic application.
i don't know how to deal with this problem.
One way out of this situation is using abstractions
E.g:
abstract class User extends ActiveRecord{
// abstract method that should overrided child classes
abstract function tableName();
}
class Admin extends User {
function tableName() { return 'admin'; }
}
class Employee extends User {
function tableName() { return 'employee'; }
}
But, it's depended on your exact situation. Also you can use setTableName() method for override only table name in the same class.
I agree that it's better to use some common user table. But if you still want to use 2 tables you can do that like this
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user) {
$this->addError('password', 'Incorrect username or password.');
return ;
}
if (!$user->validatePassword($this->password)) { // you need to implement this method for both models
$this->addError('password', 'Incorrect username or password.');
return ;
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if (!$this->_user) {
$this->_user = Employee::findByUsername($this->username);
}
if (!$this->user) {
$this->_user = Admin::findByUsername($this->username);
}
return $this->_user;
}
}

Extending Illuminate\Http\Request clears Accept header

I've extended the Illuminate\Http\Request class and am passing it along to my controller.
In my controller, I check if the request has an Accept: application/json header, using the $request->wantsJson() method.
If I use the base Illuminate\Http\Request class it works perfectly fine, but if I use my extended class, it says that the Accept header is null.
use Illuminate\Http\Request;
class MyRequest extends Request
{
...
}
Controller
class MyController
{
public function search(MyRequest $request) {
if ($request->wantsJson()) {
// return json
}
// return view
}
}
This does not work. If I instead replace MyRequest with an instance of Illuminate\Http\Request it works. If I var_dump $request->header('Accept'), it's NULL when using MyRequest.
Extend Illuminate\Foundation\Http\FormRequest instead:
use Illuminate\Foundation\Http\FormRequest;
class MyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
];
}
}
The FormRequestServiceProvider performs a series of configuration steps that set up the request. You could replicate that in your own service provider, of course.