I've been searching the web for how to get POST data inside the controller, so far I have found two solutions: Input::get() and $_POST.
The comment for Input::get() reads:
/**
* Gets a "parameter" value.
*
* This method is mainly useful for libraries that want to provide some flexibility.
*
* Order of precedence: GET, PATH, POST
*
* Avoid using this method in controllers:
*
* * slow
* * prefer to get from a "named" source
*
* It is better to explicitly get request parameters from the appropriate
* public property instead (query, attributes, request).
*
* #param string $key the key
* #param mixed $default the default value
* #param Boolean $deep is parameter deep in multidimensional array
*
* #return mixed
*/
What is this "named" source they refer to? What is it I should use instead of Input::get() ?
The documentation shows you can retrieve an input value for any HTTP verb by using Input::get().
$name = Input::get('name');
TO get all the inputs use Input::all() method.
To check if specific column exists use Input::has('column_name') eg.Input::has('name').
To retrieve column value use Input::get('column_name') eg. Input::get('name').
You can get a parameter from url using :-
request()->urlParam;
if you want to get GET parameter using :-
$request->get('current-password');
if you want to get POST parameter using :-
$request->post('current-password');
In modern Laravel installs, if your controller method is passed an instance of Request then you can use that. For example, all these are identical:
public function update(Request $request, Model $model) {
$some_var = $_POST["some_var"];
$some_var = $request->input("some_var");
$some_var = $request->post("some_var");
$some_var = $request->some_var;
}
If your method is not passed an instance of the current Request you can use the request() helper method to access one.
Related
I'm working on a Laravel web project that is fully integrated with external/remote Rest API. I'm trying to pass a model object that returned from API to a GET route by implicitly route binding but the default behavior that Laravel did is trying to reference this model object from the database while no database connection defined in my application.
You can customize the resolution logic:
class ApiModel
{
/**
* Retrieve the model for a bound value.
*
* #param mixed $value
* #param string|null $field
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value, $field = null)
{
return Http::get('api/path/for/model')->json();
}
}
If you need to further modify the model class to have an eloquent-like model, you can use or borrow from jenssegers/model.
I am using Laravel and eclipse as my IDE. I am using the laravel-ide-helper package for autocompletion.
I am calling methods from an eloquent model object.
When I type in
User::find
eclipse provided me with:
find($id, $columns) : \Illuminate\Database\Eloquent\Model.
which means the "find" method returns an \Illuminate\Database\Eloquent\Model instance.
However, when I type in
User::where
eclipse provided me with the following:
where($column, $operator, $value, $boolean) : $this
which means the function "where" returns
$this
Now, I don't really know what $this means because as I understand it "where" should return a query builder instance. As far as I know, $this means the object caller of the method (in this context, the User model itself). But it clearly does not return the model. I suspect that I do not understand what $this means in this context.
What am I missing?
The find() and where() methods do not exist on the Model class, so calls to these methods ends up falling through to the PHP magic method __call() which Laravel has defined. Inside this magic method, Laravel forwards the method call to a new query builder object, which does have these methods.
The query builder class' find() method returns a Model, and its where() method returns a reference to itself ($this) so that you can fluently chain more method calls to the builder.
All of this can make it hard for an IDE to provide hints (IntelliSense), which is where packages like laravel-ide-helper come in. They basically generate files full of interfaces that your IDE can use to understand what magic methods and properties exist for various classes, but in some cases these method signatures still fall short of what you might like to know about the code structure.
In this case the IntelliSense suggestions are apparently populating from the docblock for \Illuminate\Database\Eloquent\Builder::where():
/**
* Add a basic where clause to the query.
*
* #param string|array|\Closure $column
* #param mixed $operator
* #param mixed $value
* #param string $boolean
* #return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and');
You can see that the return type is defined as $this. At this point, some IDEs may be smart enough to understand the meaning and provide suggestions for an instance of that class. However, this could become more complicated if the method definitions your IDE is parsing are being generated by packages like laravel-ide-helper. In that case it depends not only on the capabilities of your IDE, but also on the output of the helper package.
Eclipse works purely off the method comments in the source code for its hints, so if you look at the source code for Builder which is the returned type of query(), it has for find...
/**
* Find a model by its primary key.
*
* #param mixed $id
* #param array $columns
* #return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
*/
public function find($id, $columns = ['*'])
for where() it is...
/**
* Add a basic where clause to the query.
*
* #param string|\Closure $column
* #param string $operator
* #param mixed $value
* #param string $boolean
* #return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
As it can only add one type hint it uses the first from find() which is \Illuminate\Database\Eloquent\Model and the only option from where() is $this.
I'm trying to define a param for a method as being the ID field from another class. Basically this idea...
/**
* #param \Database\Member::id $memberId
* #return MemberEntity
*/
public function getMember( int $memberId ) : MemberEntity
{
...
}
the #see command doesn't seem to be the right solution for this. Is there something I'm missing here? The PHPDoc website is surprisingly minimal...
thanks!
The #param tag receives the values: type, name and description. Apparently the type of your variable is int. If the \Database\Member::id attribute is not a native type of php or a class, it can not be used that way. So it is not possible to do this type of reference you want in traditional PHPDoc.
Syntax
#param [Type] [name] [<description>]
I am using Symfony 3 and I've created a custom Voter class.
I want to access it using the SensioFrameworkExtraBundle #Security tag.
It kind of works.
If I do the following it works perfectly:
/**
* #Rest\Get("organisation/{id}")
* #Security("is_granted('OrgAdmin', id)")
* #param int $id
* #param Request $request
*
* #return View
*/
public function getOrganisationAction($id, Request $request)
{
But I don't like the idea of using magic strings in the application and I would much rather use a class constant for the check.
Something like this:
/**
* #Rest\Get("organisation/{id}")
* #Security("is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)")
* #param int $id
* #param Request $request
*
* #return View
*/
public function getOrganisationAction($id, Request $request)
{
But when I try that I get the following error message:
Unexpected character \"\\\" around position 20 for expression `is_granted(AppBundle\\OrgRoles::ROLE_ADMIN, id)`.
Which when unescaped, is the following:
Unexpected character "\" around position 20 for expression `is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)`.
So I'm stumped on this.
Can it be done?
Any suggestions on a better way to do this?
You can use the constant() function available in the Expression Language Component:
#Security("is_granted(constant('\\Full\\Namespace\\To\\OrgRoles::ROLE_ADMIN'), id)")
Doctrine annotation reader has made this even easier for constants in PHP code:
use MyCompany\Annotations\Bar;
use MyCompany\Entity\SomeClass;
/**
* #Foo(PHP_EOL)
* #Bar(Bar::FOO)
*/
This also works just as expected for #Security / #IsGranted.
https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/custom.html#constants
I have an Eloquent model. Whenever it is retrieved from the database I would like to check whether a condition is fulfilled and set a model attribute if this is the case.
EDIT: I initially thought that the restoring event would be the right place to put the relevant logic, but as Tyler Crompton points out below, restoring is fired before a soft-deleted record is restored.
You have two valid options:
You can subclass \Illuminate\Datebase\Eloquent\Model to add such an event.
You can modify your copy of \Illuminate\Datebase\Eloquent\Model to add this (and possibly send an (unsolicited) pull request to Laravel on GitHub). According to Issue 1685, it looks as though they do not want it.
If I were you, I'd go with the first option and this is how I'd do it:
<?php namespace \Illuminate\Database\Eloquent;
abstract class LoadingModel extends Model {
/**
* Register a loaded model event with the dispatcher.
*
* #param \Closure|string $callback
* #return void
*/
public static function loaded($callback)
{
static::registerModelEvent('loaded', $callback);
}
/**
* Get the observable event names.
*
* #return array
*/
public function getObservableEvents()
{
return array_merge(parent::getObservableEvents(), array('loaded'));
}
/**
* Create a new model instance that is existing.
*
* #param array $attributes
* #return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = array())
{
$instance = parent::newFromBuilder($attributes);
$instance->fireModelEvent('loaded', false);
return $instance;
}
}
Just make sure the models in question subclass from LoadingModule. I have confirmed this to work as I found a great use case for it. Older versions of PHP returned MySQL values as strings. Normally, PHP will silently cast these to their respective numeric types in numeric operations. However, converting to JSON is not considered a numeric operation. The JSON values are represented as strings. This can cause problems for clients of my API. So I added a loaded event to my models to convert values to the correct type.
You could do this on the way in, or the way out. It seems like you wanted it stored in the database, so you could use mutators.
class Foo extends Eloquent {
public function setBAttribute($value)
{
if ($this->attributes['a'] == $this->attributes['b']) {
$this->attributes['b'] = 1;
}
}
}
When ever B is set, it will check against A, and store 1 in B.
Side note: Note the B between set and attribute
I think this is the best option you can use.
The retrieved event will fire when an existing model is retrieved from the database. for example, if you have a User model in your application you must define code like below in User Model.
self::retrieved(function (self $model){
//all your code here
});