REST API post field validation Laravel 5.1 - php

I need to check if I have all posted variables are required or else throw error.
Till Now I am doing like this
Routes.php
Route::post('/api/ws_fetchuser', 'UserController#fetch_user_details');
UserController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function fetch_user_details(Request $request)
{
if(!empty($request) && $request->id!='')
{
print_r($request->id);
}
else
{
return response(array(
'error' => false,
'message' =>'please enter all form fields',
),200);
}
}
}
I am checking like this $request->id!='', is there any validation rules or methods which I can use to check id is required field.
I have added this validation in my controller as well but what if id is not present how can I show the error?
Updated Validation Code:
public function fetch_user_details(Request $request)
{
$this->validate($request, [
'id' => 'required'
]);
print_r($request->id);
}

$this->validate() methods designed to redirect back when validation failed, So instead of that you can create a validator instance and get the error list manually.
use Validator;
$validator = Validator::make($request->all(), [
'id' => 'required'
]);
if ($validator->fails()) {
return json_encode($validator->errors()->all());
}

Related

Laravel-5.5: Why does not work my validator code?

I have simple function for check sender email.
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
protected function validator(array $data)
{
return Validator::make($data, [
'recipient' => 'required|email|exists:users,email',
'sender' => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('email', Auth::user()->email);
}),
],
], $this->validator_messages());
}
Why not work this code? I only must check sender email with auth user email.
You don't need to make a query in DB, because auth()->user() object is already loaded. So, you could use the In rule:
'sender' => [
'required',
Rule::in([auth()->user()->email]),
],
],
I think you must create a rule class for validation for example:
php artisan make:rule TestUserRule
And in this class implement 2 method : passes($attribute, $value) and message methods.
For example:
public function passes($attribute,$value){
//write your conditions here you must return boolean value here
return User::where('email',Auth::user()->email)->count();
}
Or you can use laravel default exists validation rule

custom validation error format laravel 5.2

I want custom validation json response for API. Right now default error message something like this
{"password":["The password must be at least 6 characters."],"type":["The type field is required."]}
I want
{flag:0,msg:"The password must be at least 6 characters.",data:{"password":["The password must be at least 6 characters."],"type":["The type field is required."]}}
And I want this format for my REST API only. How can I achieve it.
I found solution.
I chnaged my parent controller and added formatValidationErrors method. Here it is
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Contracts\Validation\Validator;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
protected function formatValidationErrors(Validator $validator)
{
$res = $validator->errors()->all();
if(\Request::wantsJson())
{
$res = ["flag" => 0,
"msg" => $validator->errors()->first()];
$res['data'] = $validator->errors()->all();
}
return $res;
}
}
The validation fires the HttpResponseException which we can catch and act upon
Do the following in your controller action
public function abc(Request $request)
{
//using try catch to catch the validation exception thrown
try{
$this->validate($request, $rules);
}catch(\Illuminate\Http\Exception\HttpResponseException $e){
//fetching the error messages
$messages = $e->getResponse()->getSession()->get('errors')->getMessages();
//or you can use $messages = session()->get('errors')->getMessages();
$messages = collect($messages);
$content = [
'flag' => 0,
'data' => $messages->toArray(),
'msg' => $messages->first()[0]
];
return response()->json($content, 400);
}
}

How to validate and create on laravel 5.2 on controller?

Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class invitacionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
return view('administrar');
}
public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);
/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);
return redirect('/administrar');
}
}
If the relationship is properly configured, the first (commented) method should be working.
As for the second method, I think you are adding extra brackets:
DB::table('invites')->insert([
'usuId' => $request->user()->id, // <---
'code' => str_random(40),
'email' => $request->input('email')
]);
That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:
return $this->hasMany('App\Comment', 'foreign_key');
So I think you should do
public function invites()
{
return $this->hasMany(Invite::class, 'usuId');
}

using different table to authenticate user in laravel 5

I have created separate table called subscribers in mysql changed config/auth.php settings to 'model' => App\Subscribers::class, 'table' => 'subscribers'.
I have login form on home page, that submits to the home page.
so in routes i have below
Route::get('/', function () {
return view('home');
});
Route::post('/', 'LoginController#validate');
my LoginController
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function validate()
{
// attempt to do the login
$auth = Auth::attempt(
[
'email' => strtolower(Input::get('email')),
'password' => Hash::make(Input::get('password'))
]
);
if ($auth) {
return Redirect::to('dashboard');
}
}
}
when i login i get below error
Declaration of App\Http\Controllers\LoginController::validate() should be compatible with App\Http\Controllers\Controller::validate(Illuminate\Http\Request $request, array $rules, array $messages = Array, array $customAttributes = Array)
You can't use 'validate' as a name for a function. It will conflict with:
App\Http\Controllers\Controller::validate
Also add an 'else' to your if statement so if your authentication fails you can redirect the user back to the login screen for example.

Error on insert data into database using laravel5

I am new in laravel5 Framework. when I insert data into database using laravel5 at that time I get error like....
FatalErrorException in ClientFormRequest.php line 10:
Cannot make static method Symfony\Component\HttpFoundation\Request::create() non static in class App\Http\Requests\ClientFormRequest
my all files are below...
app/Http/Controller/RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use Illuminate\Http\Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
app/Http/Requests/ClientFormRequest.php
<?php namespace App\Http\Requests;
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
/**
* 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()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
public function create(array $data)
{
return client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
Routes
Route::get('client', 'RegisterController#create');
Route::post('contact_store', 'RegisterController#store');
First of all, i would suggest you to watch Laravel 5 Fundamentals repeatedly since it is free. Other series also give great information.
Secondly, I would suggest you to use at least Sublime Text and some useful packages to be able to inspect the depth nested relations of system files (Namespaces, Interfaces, Inheritance Tree etc...). If you can't/might not, this friend will serve you anytime Laravel API
Third, AFAIK, Laravel Request is build onto the Symfony' Request Component. Since you are trying to overload one of its core function as non static, you are getting this error.
In addition, to be honest, i wouldn't put my user/client model creation logic into the requests. Laravel provides an good example for this kind of misconception. In the App\Services folder, you will find a registrar service for Laravel oem user model.
Let's inspect the problem with different cases.
but first, basic...
Lets assume that all logic should be put inside the controller.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store()
{
$data = Request::all(); //requested data via Facade
//prepare validatation
$validation = Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
// create the client
Client::create([
'fullname' => Request::input('fullname'),
'email' => Request::input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
Second Solution
You might be willing to separate the validation logic and apply some dependency injection.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
ClientFormRequest.php
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users'
];
}
}
Third Solution
You might be willing to take things further and even separate the object creation logic as an service to use it anywhere. Now your request file would stay the same. However,
RegisterController.php
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use App\Services\ClientRegistrar;
class RegisterController extends Controller {
private $registrar;
public function __construct(ClientRegistrar $registrarService)
{
$this->registrar = $registrarService;
}
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
$newClient = $this->registrar->create($request->all());
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!')->compact('newClient');
}
}
App\Services\ClientRegistrar.php
use App\Client;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
class ClientRegistrar implements RegistrarContract {
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
/**
* Create a new client instance after a valid registration.
*
* #param array $data
* #return Client
*/
public function create(array $data)
{
// create the client
return Client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
To My Conclusion
There is no correct and best way to solve a problem. Stay with the best applicable and appropriate way for you and your project scale.
You also might be interested in;
Jeffrey Way's Laravel Auto Validate on Save
The error message tells you that you are overriding the create method in the ClientFormRequest class. So remove the method there. Instead create the new Client in your Controller.
Below I updated your classes to reflect the changes.
ClientFormRequest
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
}
RegisterController
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// ClientFormRequest was valid
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}

Categories