Laravel ajax post with request - php

I can't use the Request class in laravel for a Ajax request and the input request.
I'm trying to call a ajax request to the controller and this works until I wanted to request the data that has been posted to the controller. This has somthing to do with the Request class that I use.
use Request;
This class is used by the Ajax Request
use Illuminate\Http\Request;
This is the class used to request the input.
The problem is that I cannot use them both.
public function postQuestion(Request $request) {
//dd($request->answer);
if(Request::ajax()) {
// $answer = new Answers;
// $answer->answer = $request->answer;
// $answer->description = "Test";
// $answer->Questions_id = 1;
// $answer->save();
return Response::json($request->answer);
}
}
This is my code what i've wrote.
Anyone seeing somthing familiar? Or has a answer for it?

Issue turned out to be not being able to use two classes with same namespace. For such a case, PHP provides the as keyword.
use Illuminate\Http\Request as HttpRequest;
use Some\Other\Namespace\Request;
then in code both these classes can be used. E.g. HttpRequest::method() and Request::method()

you can use?
public function postQuestion(Requests\ModelRequest $request) { //your logic }
replace your Model in Requests\ModelRequest

Related

Slim Controller Request, response and args not available

What I need is : Use a custom class to receive a HTTP Request and deal with it.
What I have so far:
$app->group('/user', function () use ($app) {
$app->post('/login', Auth::class . ':login');
}
And in my Auth Class:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
// also tried: use Slim\Http\Request; use Slim\Http\Response;
class Auth {
protected $container;
public function __construct(&$c) {
$this->container = $c;
}
public function login(Request $request, Response $response, $args) {
// NEED TO GET GET/POST/PUT Params here
// When I Try to print $request, $response or $args, it returns empty
}
My code shows in the function login what I need : get the http params, and the request/response/args params. ( I want to implement many functions in one class, I mean, I don't want to use __invoke())
Another thing I don't understand is, if I do something like
return $response->withJson($somearraydata,200);
the variable $response actually works. Why?
Thanks for any help!
I think I have figured it out,
$args are never set (unless it is a get),but request and response are.
and, to get params, I could do:
$request->getParsedBody()['attribute']
Hope this helps someone. :)

Saving object in a class variable and using it in another function - php, laravel

So here's the code
use App\Video;
class HomeController extends Controller
{
protected $video;
public function index()
{
// $video_to_watch is fetched from db and I want to save it and use it in
// another function in this controller
$this -> video = $video_to_watch;
return view('home', compact('video_to_watch'));
}
public function feedback(Request $request)
{
dd($this -> video);
}
}
feedback returns null for some reason.
when I put the
dd($this -> video);
in index() it works fine, not null.
I have tried what's suggested here: Laravel doesn't remember class variables
but it didn't help.
I'm sure it's something stupid I'm overlooking. But can't seem to figure out what, any help much appreciated.
You can't keep your $video value between 2 different requests. You have to fetch your video data in each request.
use App\Video;
class HomeController extends Controller
{
public function index() {
$myVideo = $this->getMyVideo();
return view('home', $myVideo);
}
public function feedback(Request $request) {
dd($this->getMyVideo);
}
private function getMyVideo() {
// fetch $video_to_watch from db
return $video_to_watch ;
}
}
First of all don't fetch data inside a Controller. It's only 'a glue' between model and view. Repeat. No fetching inside a controller.
Use domain services and dependency injection to get business data and if you want to share this data create shared service (single instance).
-
Putting a data object into a controller property class makes a temporary dependency between method calls. Avoid it. Use services instead.

laravel: http request gave error

My idea is to send https request to all the URLs saved in my database using a model called Notifications.
class guzzleController extends Controller
{
public function guzzle() {
$client = new Client();
$notes=Notification::all();
$response = $client->get($notes);
$response=$response->getStatusCode();
var_dump($response);
}
}
For some reason the get method expects string, and it gave me an error:
InvalidArgumentException in functions.php line 62: URI must be a string or UriInterface
How can I fix this? Anyone with a better idea?
this is actually my notification class
namespace App;
use App\Status;
use App\Notification;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
You're just saying you're using a Client class but there's no trace of use statements here because you're not showing all the code that is needed for us to figure this out. We don't even know what are the get method parameters. My guess is that you're getting an array of Notification class entities back from this statement: $notes=Notification::all();.
So first of all you should be iterating over them and then you call the client on each one of them. But also then you may need to provide just a string to the get method. Can't say how since there's no code about the Notification class as well.
EDIT:
Given the code you provided I think you should try with something like this:
class guzzleController extends Controller
{
public function guzzle()
{
$client = new Client();
$notes = Notification::all();
foreach ($notes as $note) {
$response = $client->get($note->website_url);
$response = $response->getStatusCode();
var_dump($response);
}
}
}
As the error message says, the guzzle client's get() method accepts either a string or a UriInterface implementation. You're fetching the data from Notification model (which returns a Illuminate\Support\Collection not an array of URIs) and feed it directly to the client. You need to prep your data for the client. Something like this:
use Notification;
use GuzzleHttp\Client;
class GuzzleController extends Controller
{
public function guzzle()
{
$client = new Client();
$notes = Notification::all();
// To do this in a more Laravelish manner, see:
// https://laravel.com/docs/5.3/collections#method-each
foreach ($notes as $note) {
// Assuming that each $note has a `website_url` property
// containing the URL you want to fetch.
$response = $client->get($note->website_url);
// Do whatever you want with the $response for this specific note
var_dump($response);
}
}
}

get $_post in laravel from javascript $.post

I have an html with a script that is like so (btw, HAVe to use old fashioned post in my html for reasons)...
#extends('layout')
// ... includes for jquery and ajax
<script>
var theVariableINeedInLaravel = "SomeInterestingStringI'mSure"; // in reality, this is a stringify.
$.post ("foo", function(theVariableINeedInLaravel) {
}
</script>
#stop
Then in routes.php...
<?php
Route::post('foo', 'ThatOneController#getValue');
?>
Then, in the related controller....
ThatOneController.php
class ThatOneController extends \BaseController{
public function getValue(){
error_log(print_r($_POST,true)); // returns nothing.
error_log(print_r(input::all()); // returns nothing.
}
}
Or, an alternate version of the function...
public function getValue(Request $request){
error_log(print_r($request->all()); // returns nothing.
}
None of them seem to work. How can I get my post variable?
try this
use Request;
class ThatOneController extends \BaseController{
public function getValue(){
print_r(Request::all());
}
Turns out that even if $_post isn't always accessible from inside a controller function, it is directly accessible from Routes. It's a bit hacky, and "not the laravel way" but you can use $_post in routes to get and pass into other variables to get back into the normal flow.

How can I check if request was a POST or GET request in Symfony2 or Symfony3

I just wondered if there is a very easy way (best: a simple $this->container->isGet() I can call) to determine whether the request is a $_POST or a $_GET request.
According to the docs,
A Request object holds information about the client request. This
information can be accessed via several public properties:
request: equivalent of $_POST;
query: equivalent of $_GET ($request->query->get('name'));
But I won't be able to use if($request->request) or if($request->query) to check, because both are existing attributes in the Request class.
So I was wondering of Symfony offers something like the
$this->container->isGet();
// or isQuery() or isPost() or isRequest();
mentioned above?
If you want to do it in controller,
$this->getRequest()->isMethod('GET');
or in your model (service), inject or pass the Request object to your model first, then do the same like the above.
Edit: for Symfony 3 use this code
if ($request->isMethod('post')) {
// your code
}
Or this:
public function myAction(Request $request)
{
if ($request->isMethod('POST')) {
}
}
Or this:
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
if ($request->getMethod() === 'POST' ) {
}
Since the answer suggested to use getRequest() which is now deprecated,
You can do it by this:
$this->get('request')->getMethod() == 'POST'
In addition - if you prefer using constants:
if ($request->isMethod(Request::METHOD_POST)) {}
See the Request class:
namespace Symfony\Component\HttpFoundation;
class Request
{
public const METHOD_HEAD = 'HEAD';
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_PUT = 'PUT';
public const METHOD_PATCH = 'PATCH';
public const METHOD_DELETE = 'DELETE';
You could do:
if($this->request->getRealMethod() == 'post') {
// is post
}
if($this->request->getRealMethod() == 'get') {
// is get
}
Just read a bit about request object on Symfony API page.

Categories