Check if request is GET or POST - php

In my controller/action:
if(!empty($_POST))
{
if(Auth::attempt(Input::get('data')))
{
return Redirect::intended();
}
else
{
Session::flash('error_message','');
}
}
Is there a method in Laravel to check if the request is POST or GET?

According to Laravels docs, there's a Request method to check it, so you could just do:
$method = Request::method();
or
if (Request::isMethod('post'))
{
//
}

The solutions above are outdated.
As per Laravel documentation:
$method = $request->method();
if ($request->isMethod('post')) {
//
}

I've solve my problem like below in laravel version: 7+
In routes/web.php:
Route::post('url', YourController#yourMethod);
In app/Http/Controllers:
public function yourMethod(Request $request) {
switch ($request->method()) {
case 'POST':
// do anything in 'post request';
break;
case 'GET':
// do anything in 'get request';
break;
default:
// invalid request
break;
}
}

Of course there is a method to find out the type of the request, But instead you should define a route that handles POST requests, thus you don't need a conditional statement.
routes.php
Route::post('url', YourController#yourPostMethod);
inside you controller/action
if(Auth::attempt(Input::get('data')))
{
return Redirect::intended();
}
//You don't need else since you return.
Session::flash('error_message','');
The same goes for GET request.
Route::get('url', YourController#yourGetMethod);

Use Request::getMethod() to get method used for current request, but this should be rarely be needed as Laravel would call right method of your controller, depending on request type (i.e. getFoo() for GET and postFoo() for POST).

$_SERVER['REQUEST_METHOD'] is used for that.
It returns one of the following:
'GET'
'HEAD'
'POST'
'PUT'

Related

Using url parameter in route to use in conditional

I'm trying to find the correct way to lay this out in laravel so that I can hit one GET route which calls a single function, but within that function I want to use data from a mysql table to determine which blade to show.
Say this URL is visited with a query string parameter:
www.testsite.com?email=testEmail.com
I hit this route (But not sure how to accept the parameter)
Route::get('register', 'Data\DataController#DataForm')
->name('Data.register');
I have a mysql table called dataTable set up like so
email | type
-------------------------
test1#mail.com A
test2#mail.com B
test3#mail.com C
What's the best way to incorporate the email parameter so that I can hit the single route and single function, then use the email/type columns from mysql to determine the appropriate blade to show?
public function DataForm(Request $request)
{
//query table based on query string parameter 'email'
$email = dataTable::where('email', /*email parameter?*/)->first();
if($email['type']== A){
return view('data.typeA');
}elseif($email['type']== B){
return view('data.typeB');
}elseif($email['type']== C){
return view('data.typeC');
}
}
You can add it as a route parameter :
Route::get('register/{email}', 'Data\DataController#DataForm')->name('Data.register');
And then inside controller :
public function DataForm($email)
{
// Abort to 404 if $email is not a valid email address
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
abort(404);
}
$typeData = Model::where('email', $email)->first();
// Email not found in the database
if(!$typeData){
abort(404);
}
switch ($typeData->type) {
case 'A':
return view('data.typeA');
case 'B':
return view('data.typeB');
case 'C':
return view('data.typeAC');
default:
abort(404);
}
}
Using a slash in the route you should be able to pass it like this:
Route::get('register/{email}', 'Data\DataController#DataForm')
->name('Data.register');
Then in your function you can just use the variable $email and it contains the email in the URL. But not sure if this URL is OK, using a slash instead of '?email=' for the passing of the parameter.
More on there here:
https://laravel.com/docs/5.7/routing#required-parameters
You'd need more logic than this, obviously:
public function DataForm(Request $request)
{
$type = (dataTable::where('email', $request->query->get('email'))->first())['type'];
return view('data.type'.$type);
}
As others said you could auto type in Request $request; however you don't have to. You can keep the function definition without the passed parameter, and use the helper functions instead:
if(request()->has('email')) {
$email = request()->input('email');
// Do stuff
} else {
// No email supplied
}

functions in a php router

I have been trying to create a router for my php app,I am kinda new to mvc. I did some research and landed on a tutorial at requiremind.com that helped me do this. How ever there is this line of code that has been making me pull out my hair.
this is my code for the router.
<?php
function call($controller, $action) {
// require the file that matches the controller name
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'pages':
$controller = new PagesController();
break;
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array('pages' => ['home', 'error']);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('pages', 'error');
}
} else {
call('pages', 'error');
}
?>
this is the part giving me headache $controller->{ $action }();.
The comment says it calls the action . But i do not have a function like action() anywhere.
I know there are different ways of creating a router but I would really want to understand how this particular one works.
I need someone to kindly help me understand what this part of the code does.
Use method_exists func
if(method_exists($controller, $action)) {
$controller->$action();
}
In this particular m-v-c application , looks like the author wanted the function call() to be the main function of the application , you analyze the request then call the function call with the appropriate controller and action. here is usage example of this code,
<?php
$path = trim(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/");
$pathParts = explode("/", $path);
switch ($pathParts[0]){
//www.example.com/home
case "home":
call("homePageController",'showPagefunction');
break;
//www.example.com/contact
case "contact":
if ($_SERVER['REQUEST_METHOD'] == "GET"){
call("contactPageController",'showPageFunction');
}else if($_SERVER['REQUEST_METHOD'] == "POST"){
call("contactPageController",'postContactMsgFunction');
}
break;
default:
header("HTTP/1.0 404 Not Found");
die("404 error");
}
That line calls a method named as specified in the value contained in the variable $action, so for example edit or delete. It is sometimes referred to as variable method call.
This answer was submitted by #arkaschar in the comments section

Laravel Form Request not being passed to argument

I'm busy migrating an app from Laravel 4.2 to 5.1, and am experiencing an issue with Form Requests. It's probably something simple that I'm missing - not really sure.
The method below is meant to attempt a sign in if SignInRequest successfully authorises the request. However, if the validation passes, SignInRequest is not passed to attemptSignIn, which throws the process off with this error:
Argument 2 passed to App\Http\Controllers\Auth\AuthController::attemptSignIn() must be an instance of App\Http\Requests\SignInRequest, none given
This is the method (controller is AuthController) in question, which tries to sign in using a username or an email address:
public function attemptSignIn($type = 'regular', SignInRequest $request)
{
switch ($type) {
case 'regular':
$identifierFieldName = 'account_identifier';
$field = filter_var($request->input($identifierFieldName), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input($identifierFieldName)]);
$specifics = $request->only($field, 'passphrase');
$specifics['activated'] = (int) true;
if ($this->auth->attempt($specifics)) {
return redirect()->intended($this->redirectPath);
} else {
return redirect($this->signInPath)
->with('authError', "The credentials you've provided are incorrect.")
->with('authErrorType', 'warning')
->withInput($request->only($identifierFieldName))
->withErrors();
}
break;
case 'oota':
break;
default:
return redirect($this->signInPath);
break;
}
}
The form request is straight-forward, specifying rules, messages and authorize (return true).
If the validation fails, however, SignInRequest is passed to the method, and the errors are shown accordingly.
Am I missing anything here?
use \path\to\your\ClassRequest as MyRequest
or
protected $myrequest;
public function __construct(\path\to\your\ClassRequest $request){
$this -> myrequest = $request; // use directly in your method or any method
}
Hope this help.
public function post_form(MyRequest $request) {
your code here
}

Laravel - check if Ajax request

I have been trying to find a way to determine Ajax calls in Laravel but I have not found any documentation about it.
I have an index() controller function where I want to handle the response differently based on the nature of the request. Basically this is a resource controller method that is bound to GET request.
public function index()
{
if(!$this->isLogin())
return Redirect::to('login');
if(isAjax()) // This is what I am needing.
{
return $JSON;
}
$data = array(
'records' => $this->table->fetchAll()
);
$this->setLayout(compact('data'));
}
I know the other methods of determining the Ajax request in PHP but I want something specific to Laravel.
Thanks
Updated:
I tried using
if(Request::ajax())
{
echo 'Ajax';
}
But I am receiving this error:
Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context
The class shows that this is not a static method.
Maybe this helps. You have to refer the #param
/**
* Display a listing of the resource.
*
* #param Illuminate\Http\Request $request
* #return Response
*/
public function index(Request $request)
{
if($request->ajax()){
return "AJAX";
}
return "HTTP";
}
$request->wantsJson()
You can try $request->wantsJson() if $request->ajax() does not work
$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.
By default Laravel set this header in js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.
But $request->wantsJson() will check the axios query without the need for a header X-Requested-With:
// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or
\Request::wantsJson() // not \Illuminate\Http\Request
To check an ajax request you can use if (Request::ajax())
Note:
If you are using laravel 5, then in the controller replace
use Illuminate\Http\Request;
with
use Request;
I hope it'll work.
You are using the wrong Request class. If you want to use the Facade like: Request::ajax() you have to import this class:
use Illuminate\Support\Facades\Request;
And not Illumiante\Http\Request
Another solution would be injecting an instance of the real request class:
public function index(Request $request){
if($request->ajax()){
return "AJAX";
}
(Now here you have to import Illuminate\Http\Request)
if(Request::ajax())
Looks to be the right answer.
http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax
For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting. (Read more)
Use Request::wantsJson() for AngularJS:
if(Request::wantsJson()) {
// Client wants JSON returned
}
Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.
if(request()->ajax())
// code
public function index()
{
if(!$this->isLogin())
return Redirect::to('login');
if(Request::ajax()) // This is check ajax request
{
return $JSON;
}
$data = array();
$data['records'] = $this->table->fetchAll();
$this->setLayout(compact('data'));
}
Sometimes Request::ajax() doesn't work, then use \Request::ajax()
Do something like this
public function functionName(User $user): string
{
(string) $message = "";
// check if request is ajax
if(request()->ajax())
{
if($this->isOwner($user->id)){
$message = 'success';
}else{
$message = "You are unauthorized to perform this action.";
}
}else{
$message = 'Wrong server request';
}
return $message;
}
after writing the jquery code perform this validation in your route or in controller.
$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
console.log(data);}
});
Route::get('/', function(){
if(Request::ajax()){
return 'it's ajax request';}
});
Most of the answers are working fine. We can also check the request header
request()->header('Accept')=='application/json'
to check the request type

How can I check if request was a POST or GET request in codeigniter?

I just wondered if there is a very easy way to determine whether the request is a $_POST or a $_GET request.
So does Codeigniter have something like this?
$this->container->isGet();
I've never used codeigniter, but for this I check the $_SERVER['REQUEST_METHOD'].
Looking at the docs maybe something like:
if ($this->input->server('REQUEST_METHOD') === 'GET') {
//its a get
} elseif ($this->input->server('REQUEST_METHOD') === 'POST') {
//its a post
}
If you're going to use it a lot then it's simple to roll your own isGet() function for it.
For CodeIgniter 3 users: the docs state the input class has a function to get the request method:
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
In codeigniter 4:
$this->request->getMethod() // Returns get, post, or whatever the method is
The correct answer is:
if ($this->input->post()) {
//have post
}

Categories