Extending Illuminate\Http\Request clears Accept header - json

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.

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);

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?

Is it possible for PhpStorm to infer the return type of this method?

I imagine I might need to add a special annotation somewhere, but I'm crossing my fingers that PhpStorm is smart enough to resolve return types given awkward inheritance patterns.
For example, I have some code that resembles this:
<?php
class Collection extends \ArrayObject
{
public function __construct(array $items)
{
foreach ($items as $key => $value) {
if (isset(static::$requiredType) && !$item instanceof static::$requiredType)
$this->offsetSet($key, $value);
}
}
public function getFirst()
{
return $this->offsetGet(0);
}
}
class MessageCollection extends Collection
{
protected static $requiredType = 'Message';
}
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}
I'd like it if when I call UserCollection::getFirst() it inferred that a User was returned, while when I call MessageCollection::getFirst() it inferred that a Message was returned. Is there some annotation I could put in somewhere to achieve this result?
My first thought was something like this:
/**
* #return Message|User|XXXX|YYYY|ZZZZ|AAAA|BBBB|CCCC|DDDD
*/
public function getFirst()
{
return $this->offsetGet(0);
}
but I imagine that would get a little ridiculous to the point of being useless as I add more collection classes.
Try this:
/**
* #method \User getFirst()
*/
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}

Validating JSON input Laravel

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 ?

Laravel 4: (routing?) to search keyword url

Let's say for example in results q='sports', how would I be able to make it www.example.com/results?q=sports or whatever? And when I type manually in the url www.example.com/results?q=books it would search for books.
The response is in json btw.
You will need to process the parameter from within whatever controller '/results' is routed to, eg:
if isset($_GET['q']) {
$searchCategory = $_GET['q'];
}
Another option would be to have q as a function parameter on a controller method:
class MyController extends BaseController {
public function __construct() {}
public function getSearch($searchCategory) {
// Do Stuff
}
}
And this would be accessible via:
http://www.example.com/search/books