I'm having problems on what URL to be used to link to the php scripts in Laravel5 which I'm running at localhost at the moment. I have created a function in my controller to handle the request. Here is the function:
public function mobile_validator(Request $request) {
$method = $request->method();
if($method == 'POST') {
$username = $request->username;
$password = $request->password;
$user = DB::table('users')->get();
foreach($user as $i) {
if($username == $i->email and $password == $i->password) {
return 'success';
}
else {
return 'failure';
}
}
}
I have also created a route in my route.php.
Route::get('/mobilevalidator', 'AuthController#mobile_validator');
This is my URL in android:
private static final String LOGIN_URL = "http://10.0.2.2:8000/mobilevalidator/";
Now when I login in my app it displays the error com.android.volley.timeouterror
Is the URL correct in defining the php script in Laravel?
In your routes you defined a
Route::get
That means that this route is listening to the GET method. In your controller you specify
$method = $request->method();
if($method == 'POST') {
Which means your controller is actually only returning stuff you have a POST which will ofcourse never happen since your route calling your controller is only listening to GET
You can complety remove the check of the method. A controller method can only be called if you map the route to it. If you want to also support POST simply add
Route::post( ... )
A little hint:
Try to use PostMan or any other RestClient to test your Routes before using them in your app. Also don't forget to remove the web middleware in laravel - otherwise you will also need to add the csrf token to your request.
Related
Working on dynamic routing for all frontend urls but while accessing admin routes it goes to abort condition which is on the mentioned route's function.
Web.php
Route::get('/{slug?}', 'slug' )->where('slug','(.*)')->name('slug');
FrontController.php
public function slug(Request $request, $slug=null) {
if ($slug == "admin") {
return redirect()->route('login');
}
if (Str::contains($slug, 'admin/')) {
$routes = Route::getRoutes();
$request = Request::create($slug);
try {
$route->match($request,'admin.dashboard');
//How to access requested url's route name to redirect there
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
abort(404);
}
}
if ($slug == "login") {
return view('auth.login');
}
if ($slug == null) {
$page = Pages::where('url', '')->first();
}
if (empty($page)) {
abort(404);
}
$contentWithBlade = Blade::render($page->pages_content);
$session = $request->session()->put('key', $page);
return view('frontend.pages.template', compact('contentWithBlade', 'page'));
}
Any suggestions how to get route name against route url?
check this
Route::getCurrentRoute()->getPath();
or
\Request::route()->getName()
from v5.1
use Illuminate\Support\Facades\Route;
$currentPath= Route::getFacadeRoot()->current()->uri();
Laravel v5.2
Route::currentRouteName(); //use Illuminate\Support\Facades\Route;
Or if you need the action name
Route::getCurrentRoute()->getActionName();
Laravel 5.2 route documentation
Retrieving The Request URI
The path method returns the request's URI. So, if the incoming request is targeted at http://example.com/foo/bar, the path method will return foo/bar:
$uri = $request->path();
The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method:
if ($request->is('admin/*')) {
//
}
To get the full URL, not just the path info, you may use the url method on the request instance:
$url = $request->url();
Laravel v5.3 ... v5.8
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
Laravel 5.3 route documentation
Laravel v6.x...7.x
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
** Current as of Nov 11th 2019 - version 6.5 **
Laravel 6.x route documentation
There is an option to use request to get route
$request->route()->getName();
Latest Version of laravel
I'm using Woocommerce webhooks to listen out for every time an order is created/updated/deleted.
I've setup the webhook in Woocommerce as follows
In my Laravel routes file I have set up the route as follows:
use Illuminate\Http\Request;
// API routes...
Route::post('api/v1/orders/create', function (Request $request) {
Log::debug($request->all());
return $request->all();
});
However, when I view the logs as well as the return data in POSTMAN, all I get is an empty array.
Any HTTP method other than 'GET' throws a MethodNotAllowedException
I'm not sure of any other way in Laravel to consume data other than with Request $request.
According to my understanding of routing in Laravel, the input that you pass in to the function is meant to actually be variables for your route.
So if you had a route in your API:
api/v1/orders/{id}/create then in the route function you'd pass in id as the method argument. So this would be correct:
Route::post('api/v1/orders/{id}/create', function ($id) {
Log::debug($id);
return $id;
});
It's looking for request in your route definition.
Rather create a controller. Then in your routes.php use this:
Route::post('api/v1/orders/create', 'OrdersController#create')
That tells your routing to redirect all HTTP POST calls to api/v1/orders/create to the OrdersController.php and the create() method within that controller.
In your controller, you'll be able to use the $request variable as an input argument and it should work.
So in OrdersController.php:
class OrdersController extends Controller {
public function create(Request $request) {
Log::debug($request->all());
return $request->all();
}
}
Good Luck!
This worked for me. My route in api.php is as follow.
Route::post('/woocommerce/webhook/', 'Api\WoocommerceController#test');
And my controller action is as follow.
public function test()
{
$payload = #file_get_contents('php://input');
$payload = json_decode( $payload, true);
\Log::info(json_encode( $payload));
return response()->json([ 'data' => $payload, 'status' => \Symfony\Component\HttpFoundation\Response::HTTP_OK]);
}
I am trying to use Steam's Login With Slim Framework!
For this I am trying to use steamauth library (https://github.com/SmItH197/SteamAuthentication)
I am able to successfully require the files to slim via that start.php but how do I call the steamlogin() and logout functions?
Please help me!
You will need to add a middleware for the auth step.
Here's a simple example, assuming you are using Slim 3:
$middleware = function (Request $request, Response $response, $next) {
$this->user = null;
if(!isset($_SESSION['steamid'])) {
//don't interfere with unmatched routes
$route = $request->getAttribute('route');
if ($route && !in_array($route->getName(), ['login'])) {
return $response->withStatus(403)->withHeader('Location', $this->router->pathFor('login'));
}
} else {
include ('steamauth/userInfo.php'); //To access the $steamprofile array
//Protected content
}
return $next($request, $response);
};
$app->add($middleware);
In your /login route just include a view with steamlogin(). You can use the basic php-view template for this.
Consider the following test:
public function it_should_contain_a_list_of_investors_who_belong_to_one_or_more_investment() {
$this->createInvestment();
$investor = factory(User::class)->create([
'role_id' => 4
]);
$response = $this->actingAs($investor)
->call('GET', 'api/v1/investors?include=investments');
dd(json_decode($response->getContent()));
$this->assertNotEmpty(json_decode($response->getContent()));
}
Now consider the following action this test is calling:
public function getAllInvestorsForCompany($slug)
{
$users = $this->investorEntity->usersForCompany($slug);
$resource = new Collection($users, new InvestorTransformer, 'investor');
dd($_GET);
if (isset($_GET['include'])) {
$usersData = $this->manager->parseIncludes($_GET['include'])->createData($resource)->toArray();
} else {
$usersData = $this->manager->createData($resource)->toArray();
}
return response()->json($usersData);
}
Note the dd, the $_GET returns []
Lets do the same test in the browser:
array:1 [▼
"include" => "investments.offering.company"
]
Ok so in the browser I get back investments.offering.company, because that is what I am passing in as the ?include= But in the test its like laravel ignores the ?include and moves on.
is this a default behaviour of laravel 5.1 tests and if so how do I shut it off?
Don't use $_GET, $_POST, or $_REQUEST in Laravel controllers. You should use the Request facade:
public function getAllInvestorsForCompany($slug)
{
$users = $this->investorEntity->usersForCompany($slug);
$resource = new Collection($users, new InvestorTransformer, 'investor');
if (Request::input('include')) {
$usersData = $this->manager->parseIncludes(Request::input('include'))->createData($resource)->toArray();
} else {
$usersData = $this->manager->createData($resource)->toArray();
}
return response()->json($usersData);
}
When testing, Laravel doesn't actually make HTTP calls - it creates a Request object, and then passes that to the routing controller, which is why those variables aren't actually available.
Using the Request facade also allows you to do things like set a default if the input doesn't exist, and handles multiple input forms (like AngularJS which sends data as JSON in the request body, instead of as POST or GET parameters).
The 3rd argument for call is for parameters.
$response = $this->actingAs($investor)
->call('GET', 'api/v1/investors', ['include' => 'investments']);
A couple of questions that I cannot seem to find definative answers for, I am working on a RESTful api at the moment, that in time will interact with a handful of client devices, for the time being I am concetrating, on the API, and the web application that goes along with it.
The api lives at http://api.local and the web application lives at http://webapplication.local. The web application is a Laravel installation with a Backbone front-end.
I am trying to save some data from the Backbone to the database of the API. So the API save method looks like this,
public function store()
{
$user_details = Input::all();
$user = new User;
$user->firstname = $user_details['firstname'];
$user->surname = $user_details['surname'];
$user->email = $user_details['email'];
$user->password = Hash::make($user_details['password']);
$user->remember_token = '';
$user->save();
return Response::json($user_details, 200);
}
And it has a route that looks like this,
Route::group(['prefix' => 'api/v1'], function(){
Route::get('users', 'UsersController#index');
Route::get('users/{id}', 'UsersController#get');
Route::post('users/create', 'UsersController#store');
/**
* PUT request to edit the database record
* #todo: Need to be a PUT request in the long run
*/
Route::post('users/update/{id}', 'UsersController#update');
/**
* DELETE request to edit the database record
* #todo: Need to be a DELETE request in the long run
*/
Route::post('users/delete/{id}', 'UsersController#delete');
});
On the front end side (web application) I am saving a model like this,
saveNewUser: function(e) {
e.preventDefault()
var data = this.$el.find('.js-create-new-user').serializeJSON();
// create a new model
var User = new app.User();
User.save(data, {
success: function(model, response){
console.log(model);
console.log(response);
console.log("sucess");
},
error: function(model, response) {
console.log(model);
},
wait:true
});
}
This sends a POST request to the webapplication.local/users/create method, that looks like this,
public function create()
{
$data = Input::all();
$curl = new Curl\Curl();
$curl->post('http://pops.local/api/v1/users/create', $data);
if ($curl->error) {
return Response::json($curl->error, $curl->error_code);
}
else {
return Response::json($curl->response, 200);
}
}
If I look at the $curl->response then I see the data object that is being sent - which I assume means the cURL request is successfully being sent. However nothing gets updated in the API's database?
Am I going about this all wrong? Should Backbone be sending/making requests directly to the API, and leave the PHP behind the web application to do things that the API does not do i.e resize images etc?
You may send requests directly from backbone but you dont have to. Everything looks fine. Check what is returned from $user->save(); by writing something like that:
dd($user->save());
You should get true if everyting is fine, false if there is any error.