I working in Laravel project and I can't call static method across variable
For example:
$objName = 'User';
$objName::get();
On this way I get error.
$objName = 'User';
Is a string, for using the get() method $objName should be an object, for example:
$objName = User::all()->first(); // this will return an object
Ok I use
User::all();
But I want get parametar from URL for example www.example.com/User, www.example.com/Articles -> User and Article is parametar in URL (this is Laravel web route) and call static method. When I wrtie first URL than call User object if I write first URL than call Article object.
www.example.com/User
$param= 'User';
$param::all();
www.example.com/Article
$param= 'Article';
$param::all()
I find solution!
This solution in Laravel:
$data = call_user_func( array('\App\\'.$param , 'all'));
but if you want use in plain PHP then is:
$data = call_user_func( array($param , 'all'));
This will call Object and Method.
If you want to send arg in methond thent is:
$data = call_user_func( array('\App\\'.$param , 'all'), $arg); /*For Laravel*/
$data = call_user_func( array($param , 'all'), $arg); /*For plain PHP*/
Related
In my Symfony service I wanted to add small edit so I decided it's better to do it inside the class.
In my controller I am getting storyId (it's not table ID, it's a string with different chars) from my Request like:
$story = json_decode($request->getContent(), true);
$storyId = $story['storyId'];
$freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
$story->freeStoryName($freeStoryName);
return $this->json(["message" => "SUCCESS"]);
And In my Entity class I handle it like:
public function freeStoryName(Story $story): Story
{
$this->setPreviousStoryName($story->getStoryName());
$story->setStoryName(null);
}
And I get the error message:
Call to a member function freeStoryName() on array
I know what the message means but do not get it? It's findOne() method..
And other question will be, do I need flush() method in the Entity class like I had in a service?
You are using freeStoryName on $story which is an array (json_decode($request->getContent(), true);)
You need to use your method with your result :
$story = json_decode($request->getContent(), true);
$storyId = $story['storyId'];
$freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
$freeStoryName->freeStoryName($freeStoryName);
return $this->json(["message" => "SUCCESS"]);
If you feel that it's a little weird to do it this way, you could change your method to:
public function freeStoryName()
{
$this->setPreviousStoryName($this->getStoryName());
$this->setStoryName(null);
}
And use it:
$freeStoryName->freeStoryName();
Is it possible get the value of a route placeholder within a Slim container? I know I can access the placeholder by adding a third parameter to the request but I'd like to have it injected so I'm not assigning it on each request.
I've tried $app->getContainer('router') but I can't seem to find a method to actually pull the placeholder value.
Example:
$app = new Slim\App;
$c = $app->getContainer();
$c['Controller'] = function() {
$userId = // how do I get the route placeholder userId?
return new Controller($userId);
};
$app->get('/user/{userId}','Controller:getUserId');
class Controller {
public function __construct($userId) {
$this->userId = $userId;
}
public function getUserId($request,$response) {
return $response->withJson($this->userId);
}
}
Without some 'hacky' things this will not work because we have no access on the request object build by slim, while the controller get constructed. So I recommend you to just use the 3rd parameter and get your userid from there.
The 'hacky' thing would be todo the same, what slim does when you execute $app->run(), but if you really want todo this, here you'll go:
$c['Controller'] = function($c) {
$routeInfo = $c['router']->dispatch($c['request']);
$args = $routeInfo[2];
$userId = $args['userId'];
return new Controller($userId);
};
Note: slim3 also urldecoded this values so may do this as well urldecode($args['userId']) Source
create a container wrapper and a maincontroller then extend all your controller from your maincontroller, then you have access to the container.
here is how i solved this problem:
https://gist.github.com/boscho87/d5834ac1ba42aa3da02e905aa346ee30
I have a method, which takes a reference
// CarService.php
public function getCars(&$carCollection = null)
{
$promise = // guzzle request for getting all cars would be here
$promise->then(function (ResponseInterface $response) use (&$carCollection) {
$cars= json_decode($response->getBody(), true);
$carCollection= new CarCollection($cars);
});
}
However, when accessing the collection and trying to reuse it, I'm getting the error
Argument 1 passed to {placeholder} must be an instance of {placeholder}, null given
I know that the reason for this is, that the constructor returns nothing, but how can I still assign my variable to a new instance of the CarCollection (which extends Doctrine's ArrayCollection)
I even tried it with a static method as a work around
// CarCollection.php
public static function create(array $cars): CarCollection
{
$carCollection = new CarCollection($cars);
return $carCollection;
}
// CarService.php
public function getCars(&$carCollection = null)
{
$cars = // curl request for getting all cars would be here
$carCollection = CarCollection::create($cars)
}
but it's still null. Why is that? How can I set a referenced variable to a new class?
I access the method like this
$carService = $this->get('tzfrs.vehicle.services.car');
$carCollection = null;
$promises = [
$carService->getCars($carCollection)
];
\GuzzleHttp\Promise\unwrap($promises);
var_dump($carCollection); // null
When I set the reference directly, eg.
// CarService.php
public function getCars(&$carCollection = null)
{
$carCollection = new CarCollection([]);
}
it works without any problems. Seems like the callback is somehow the problem.
Whoever downvoted this, can you please elaborate why and why you voted to close?
I might be misunderstanding the question, but you should be able to modify an object when passing by reference. See here for an example: https://3v4l.org/KtFvZ
In the later example code that you added, you shouldn't pass $carCollection by reference, the & should only be in the method/function defintion, not provided when you call it. I don't think that is your problem though, that should be throwing an error in php7.
Hello I'm creating an API using REST and Laravel following this article.
Everything works well as expected.
Now, I want to map a GET request to recognise a variable using "?".
For example: domain/api/v1/todos?start=1&limit=2.
Below is the contents of my routes.php :
Route::any('api/v1/todos/(:num?)', array(
'as' => 'api.todos',
'uses' => 'api.todos#index'
));
My controllers/api/todos.php :
class Api_Todos_Controller extends Base_Controller {
public $restful = true;
public function get_index($id = null) {
if(is_null($id)) {
return Response::eloquent(Todo::all(1));
} else {
$todo = Todo::find($id);
if (is_null($todo)) {
return Response::json('Todo not found', 404);
} else {
return Response::eloquent($todo);
}
}
}
}
How do I GET a parameter using "?" ?
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$start = $_GET['start'];
$limit = $_GET['limit'];
EDIT
According to this post in the laravel forums, you need to use Input::get(), e.g.,
$start = Input::get('start');
$limit = Input::get('limit');
See also: http://laravel.com/docs/input#input
On 5.3-8.0 you reference the query parameter as if it were a member of the Request class.
1. Url
http://example.com/path?page=2
2. In a route callback or controller action using magic method Request::__get()
Route::get('/path', function(Request $request){
dd($request->page);
});
//or in your controller
public function foo(Request $request){
dd($request->page);
}
//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"
###3. Default values
We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals
//wrong way to do it in Laravel
$page = isset($_POST['page']) ? $_POST['page'] : 1;
//do this instead
$request->get('page', 1);
//returns page 1 if there is no page
//NOTE: This behaves like $_REQUEST array. It looks in both the
//request body and the query string
$request->input('page', 1);
###4. Using request function
$page = request('page', 1);
//returns page 1 if there is no page parameter in the query string
//it is the equivalent of
$page = 1;
if(!empty($_GET['page'])
$page = $_GET['page'];
The default parameter is optional therefore one can omit it
###5. Using Request::query()
While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string
//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');
//with a default
$page = $request->query('page', 1);
###6. Using the Request facade
$page = Request::get('page');
//with a default value
$page = Request::get('page', 1);
You can read more in the official documentation https://laravel.com/docs/5.8/requests
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController#someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
This is the best practice. This way you will get the variables from
GET method as well as POST method
public function index(Request $request) {
$data=$request->all();
dd($data);
}
//OR if you want few of them then
public function index(Request $request) {
$data=$request->only('id','name','etc');
dd($data);
}
//OR if you want all except few then
public function index(Request $request) {
$data=$request->except('__token');
dd($data);
}
Query params are used like this:
use Illuminate\Http\Request;
class MyController extends BaseController{
public function index(Request $request){
$param = $request->query('param');
}
In laravel 5.3 $start = Input::get('start'); returns NULL
To solve this
use Illuminate\Support\Facades\Input;
//then inside you controller function use
$input = Input::all(); // $input will have all your variables,
$start = $input['start'];
$limit = $input['limit'];
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Route::get('my_route/{myvalue}', 'myController#myfunction');
Step 2 : Write a function inside your controller
public function myfunction($myvalue)
{
return view('get')->with('myvalue', $myvalue);
}
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
{{ $myvalue }}
So If you have this in your url
http://127.0.0.1/yourproject/refral/this#that.com
Then it will print this#that.com in you view file
hope this helps someone.
It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.
There is at least two modes to get variables by GET in Laravel (
Laravel 5.x or greater):
Mode 1
Route:
Route::get('computers={id}', 'ComputersController#index');
Request (POSTMAN or client...):
http://localhost/api/computers=500
Controler - You can access the {id} paramter in the Controlller by:
public function index(Request $request, $id){
return $id;
}
Mode 2
Route:
Route::get('computers', 'ComputersController#index');
Request (POSTMAN or client...):
http://localhost/api/computers?id=500
Controler - You can access the ?id paramter in the Controlller by:
public function index(Request $request){
return $request->input('id');
}
If I call $this->url() from a view I get the url with parameters. Ex: /test/view/var1/value1
Is there any way to get the currect url/location without parameters (var1/value1) and without passing the urlOptions:
For example, if I use this it works:
$this->url(array("controller"=>"test", "action"=>"view"),null,true);
//Returns /test/view
But I would like to avoid passing the parameters
$this->url(array(),null,true);
Is there any way to do this?
This sounds like a job for a view helper. Something like this?
class Zend_View_Helper_Shorturl {
public function shorturl() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$module = $request->getModuleName();
$controller = $request->getControllerName();
$action = $request->getActionName();
return $this->view->url(array('module'=>$module, 'controller'=>$controller,'action'=>$action), null, true);
//return "/$controller/$action"; //Left this in incase it works better for you.
}
}
Then you just write $this->shorturl(); in your view.
Just to be clear this would go in scripts/helpers/Shorturl.php
Edit:
In fact, I've just tried this and it works. I'd say this is the solution to use.
class Zend_View_Helper_Shorturl {
public function shorturl() {
return $this->view->url(array('module'=>$module, 'controller'=>$controller,'action'=>$action), null, true);
}
}
Not really - the Zend_Controller_Request_Http object that the router (called by the url view helper) uses to generate the link doesn't really distinguish between the module/controller/action parameters and other parameters your action might use.
Either use the first form that you quoted above, or if you need a solution that works for every action/controller, create something like:
class MyApplication_Controller_Action_Base extends Zend_Controller_Action {
public function preDispatch() {
//Generate a URL to the module/controller/action
//(without any other parameters)
$this->view->bareUrl = $this->view->url(
array_intersect_key(
$this->getRequest()->getParams(),
array_flip(array('module','view','controller')
),
null,
true
);
}
}
In any view, you can then use <?=$this->bareUrl?>
Just use $this->url() to get the baseUrl/controller like it appears in the browser URL for example if your it is www.your-domain.ro/project/members it will return project/members