Laravel return values missing from documentation? - laravel

In the Laravel documentation, I can't find the possible return values are for basic Laravel functions like:
Mail::send(...) // does this return true/false if successful?
Input::get('foo') // what is returned when foo is not set?
Request::segment(2) // what is returned if there isn't a second segment?
Have I overlooked something or are we just left to trial/error to figure these out?

TL;DR
Take a look at the Laravel API website for all the source code. It's extremely well written and easy to follow. You should be able to answer all of these questions and learn new features very quickly.
=========================================
Laravel being as big and powerful as it is, makes it hard to document every little thing. However, using the API site, you can find answers to all these questions and discover TONS of neat, undocumented little tricks and treats.
Laravel API
Mail::send() Example
Take for instance your Mail::send() example. At the API site, we can search for Mail and browse to the Illuminate/Mail/Mailer.php page.
From there we can look at the code for the send() Line 94 method and see that it returns a call to $this->sendSwiftMessage($message).
From there, we can take a look at the code for the sendSwiftMessage() Line 281 method and see that it returns a call of $this->swift->send($message).
Looking through the Mail class, we learn that $this->swift is simply a instance of the Swift_Mailer class Line 56. The Laravel docs actually do mention that the Mail class is a wrapper for the popular Swift_Mailer.
Anyway, now we need to find what the send() method in the Swift_Mailer library returns. Where we see at the Swift_Mailer website, the send() method actually returns the number of recipients it was sent to, or 0 upon a failure.
Swift_Mailer itself actually have available quite a bit more useful
information, such as who the actual failed recipients were. However,
Laravel does not expose this information as of now. If you wanted to
gain access to Swift_Mailer's other features, you'd have to either
extend the Mail class or perhaps use the Swift_Mailer class
directly.
This essentially means, that yes, you can use a true/false check to determine success as 0 will evaluate to false and any positive, non zero number will evaluate to true in PHP. However, I also believe that Laravel will throw an exception if something goes wrong as it does in most cases, however this might be a, forgive the pun, exception where it will not throw an Exception.
Although that was a bit long winded, and probably one of the more complex examples. The vast majority of things Laravel provides are quick, easy to lookup and understand.
Going through the API is a great way to discover tons of undocumented features of the framework. For example, just go to the Str class and you'll see quite a few neat, useful things that you can use.
Input::get() Example
Without going into as much detail, Input::get ends up calling the array_get() helper function Link, which will return the following in order of priority.
The value stored at the key.
The default value passed to the Input::get() method.
null

Related

Can I set the record limit of Laravel's paginate method with user information?

I'm using the paginate method of the query builder and I would like to allow the user to choose the number of items per page.
$paginate= Model::paginate($request->input('per_page'));
Doing this could I be opening a loophole for SQL Injection or is this value sanitized first?
You can use a validator to make sure $request->input('per_page') is an integer or whatever validation you want.
documentation here : https://laravel.com/docs/9.x/validation
Such methods must be protected. This is what models are for.
But you are right, it's better to be safe than sorry and verify your premises. This is especially true with popular frameworks, because sometimes the creators crave for simplicity above everything else, often forgetting even security.
But it seems that in this case, Laravel QueryBuilder casts the perPage value to integer, making it immune to SQL injection:
protected function compileOffset(Builder $query, $offset)
{
return 'offset '.(int) $offset;
}
Then I dug a bit into the history, and found that the protection has been added almost a decade ago, so you can be sure that with any supported version of Laravel this part is safe.
That said, validating user input is still a good idea. Even being protected from SQL injections, you don't want any unexpected behavior. I don't think 500000 or -100 are good values whatsoever. If you can see that the data is not valid, it's a good strategy to bail off already, without waiting for some bizarre things to happen. So you may consider validating this input value just like any other input, like good programmers always do.

How to implement CAF Receiver Queueing

I'm confused by this page https://developers.google.com/cast/docs/caf_receiver_features#queueing
It seems to assume that any implementation of 'YourServer' will return synchronous results rather than promises or observables.
Does anyone have a working example where the queue is managed by an http based service?
Edit:
I've found one major problem with this page. It inconsistently names the cast.framework.QueueBase base class. In some places it correctly names it cast.framework.QueueBase while in others it names it cast.framework.messages.QueueBase. In particular, the link to the class documentation uses the wrong name. The correct link is to https://developers.google.com/cast/docs/reference/caf_receiver/cast.framework.QueueBase.
This helps a lot since it says fetchItems and its siblings return:
"(non-null Array of non-null cast.framework.messages.QueueItem or non-null Promise containing non-null Array of non-null cast.framework.messages.QueueItem)".
OK, there were bugs in the documentation. I reported these on the Google+ community and they are now fixed.
I've got a sample queueing receiver working and made a gist of it.

How to use a single AWS Lambda for both Alexa Skills Kit and API.AI?

In the past, I have setup two separate AWS lambdas written in Java. One for use with Alexa and one for use with Api.ai. They simply return "Hello world" to each assitant api. So although they are simple they work. As I started writing more and more code for each one, I started to see how similar my java code was and I was just repeating myself by having two separate lambdas.
Fast forward to today.
What I'm working on now is having a single AWS lambda that can handle input from both Alexa and Api.ai but I'm having some trouble. Currently, my thought is that when the lambda is run, there would be a simple if statement like so:
The following is not real code, just what I think I can do in my head
if (figureOutIfInputType.equals("alexa")){
runAlexaCode();
} else if (figureOutIfInputType.equals("api.ai")){
runApiAiCode();
}
The thing is now I need to somehow tell if the function is being called by an alexa or api.ai.
This is my actual java right now:
public class App implements RequestHandler<Object, String> {
#Override
public String handleRequest(Object input, Context context) {
System.out.println("myLog: " + input.toString());
return "Hello from AWS";
}
I then ran the lambda from Alexa and Api.ai to see what Object input would get generated in java.
API.ai
{id=asdf-6801-4a9b-a7cd-asdffdsa, timestamp=2017-07-
28T02:21:15.337Z, lang=en, result={source=agent, resolvedQuery=hi how
are you, action=, actionIncomplete=false, parameters={}, contexts=[],
metadata={intentId=asdf-3a2a-49b6-8a45-97e97243b1d7,
webhookUsed=true, webhookForSlotFillingUsed=false,
webhookResponseTime=182, intentName=myIntent}, fulfillment=
{messages=[{type=0, speech=I have failed}]}, score=1}, status=
{code=200, errorType=success}, sessionId=asdf-a7ac-43c8-8ae8-
bc1bf5ecaad0}
Alexa
{version=1.0, session={new=true, sessionId=amzn1.echo-api.session.asdf-
7e03-4c35-9d98-d416eefc5b23, application=
{applicationId=amzn1.ask.skill.asdf-a02e-4938-a747-109ea09539aa}, user=
{userId=amzn1.ask.account.asdf}}, context={AudioPlayer=
{playerActivity=IDLE}, System={application=
{applicationId=amzn1.ask.skill.07c854eb-a02e-4938-a747-109ea09539aa},
user={userId=amzn1.ask.account.asdf}, device=
{deviceId=amzn1.ask.device.asdf, supportedInterfaces={AudioPlayer={}}},
apiEndpoint=https://api.amazonalexa.com}}, request={type=IntentRequest,
requestId=amzn1.echo-api.request.asdf-5de5-4930-8f04-9acf2130e6b8,
timestamp=2017-07-28T05:07:30Z, locale=en-US, intent=
{name=HelloWorldIntent, confirmationStatus=NONE}}}
So now I have both my Alexa and Api.ai output, and they're different. So that's good. I'll be able to tell which one is which. but I'm stuck. I'm not really sure if I should try to create an AlexaInput object and an ApiAIinput object.
Am I doing this all wrong? Am I wrong with trying to have one lambda fulfill my "assistant" requests from more than one service (Alexa and ApiAI)?
Any help would be appreciated. Surely, someone else must be writing their assistant functionality in AWS and wants to reuse their code for both "assistant" platforms.
I had the same question and same thought, but as I got further and further in implementing, I realized that it wasn't quite practical for one big reason:
While a lot of my logic needed to be the same - the format of the results was different. Sometimes, even the details or formatting of the results would be different.
What I did was go back to some concepts that were familiar in web programming by dividing it into two parts:
A back-end system that was responsible for taking parameters and applying the business logic to produce results. These results would be fairly low-level, not entire phrases, but more a set of keys/value pairs that indicated what kind of result to give and what values would be needed in that result.
A front-end system that was responsible for handling things that were Alexa/Assistant specific. So it would take the request, extract parameters and state, call the back-end system with this information, get a result back which included what kind of reply to send and the values needed, and then format the exact phrase (and any other supporting info, such as a card or whatever) and put it into a properly formatted response.
The front-end components would be a different lambda function for each agent type, mostly to make the logic a little cleaner. The back-end components can either be a library function or another lambda function, whatever makes the most sense for the task, but is independent of the front-end implementation.
I suppose one could also this by having an abstract parent class that implements the back-end logic, and having the front-end logic be subclasses of this. I wouldn't do it this way because it doesn't provide as clear an interface boundary between the two, but its not unreasonable.
You can achieve the result (code reuse) a different way.
Firstly, create a method for each type of event (Alexa, API Gateway, etc) using the aws-lambda-java-events library. Some information here:
http://docs.aws.amazon.com/lambda/latest/dg/java-programming-model-handler-types.html
Each entry point method should deal with the semantics of the event triggering it (API Gateway) and call into common code to give you code reuse.
Secondly, upload your JAR/ZIP to an S3 bucket.
Thirdly, for each event you want to handle - create a Lambda function, referencing the same ZIP/JAR in the S3 bucket and specifying the relevant entry point.
This way, you'll get code reuse without having to juggle multiple copies of the code on AWS, albeit at the cost of having multiple Lambdas defined.
There's a great tool that supports working this way called Serverless Framework which I'd highly recommend looking at:
https://serverless.com/framework/docs/providers/aws/
I've been using a single Lambda to handle Alexa ASK and Microsoft Luis.ai responses. I'm using Python instead of Java but the idea is the same and I believe that using an AlexaInput and ApiAIinput object, both extending the same interface should be the way to go.
I first use the context information to identify where the request is coming from and parse it into the appropriate object (I use a simple nested dictionary). Then pass this to my main processing function and finally, pass the output to a formatter again based on the context. The formatter will be aware of what you need to return. The only caveat is that handling session information; which in my case I serialize to my own DynamoDB table anyway.

Laravel 4.2 force mass assignment on createOrUpdate and similar methods?

I've been working on an API for awhile now that has a sort of 'soft' api validation so I can use Backbone more easily on the front end. Basically the design principal has always been to only validate and update the attributes sent back that we care about. On the backend, I use the model's fillable array to limit this after validating the input array. This way we don't have to annoy people when they accidentally send back model data that we don't allow them to touch as the docs clearly state whats fillable. People seem to enjoy working with the API.
What we run into is a problem because we want to use things like 'createOrUpdate' for our backend stuff that's creating or updating models automatically. Basically we end up adding things to fillable that go against our user facing input validation. Trudging around the docs I came across 'forceFill' and other various 'force' methods, but noticed that they are missing from the more magical methods like 'createOrUpdate'. Seems like they should be methods, or at least boolean flags that can be passed to the methods to force, and maybe these options are built into Laravel 5+?
Before I go ahead and write my own methods in the base, I just wanted to ask if this is already built into 4.2 and I'm just missing it? I also wanted to create this thread as it may be informative to people still confused by how Laravel's mass assignment works.
If I don't get any feedback I'll probably just delete it.
Model::unguard(); is added in 5.1 https://laravel.com/docs/5.1/seeding available in 4.2.
You just call it before you create the object, and then you can fill any fields using createOrUpdate(), firstOrNew(), create() etc.
Correction, here it is in the L4.2 API: https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_unguard
see also: Model::reguard()

laravel 4 api documentation - how to quickly find functions?

I am having trouble in using documentation. Lets say I want to see the source of function
DB::transaction();
I go to http://laravel.com/api/index.html
and enter in the search form 'transaction'
Nothing is found.
I then try to go on the left to Namespaces/Database which makes sense.
And later I have no idea where to go. There is some namespaces, some classes, some interfaces. Later found out that this is in the connection class, which at first I did not even look at. Connection associates to connecting to the database, not making transaction.
And there often happens when I don't know how to quickly find things.
How do you deal with that?
I assume the documentation should be one of best developers friends, but I guess I found this function by using sublime massive search in all files.
Btw also - I lowed the Codeigniter documentation, so thats why also I am disapointed. In codeigniter everythign looked so simple and search worked very well. Typing same word 'transaction' finds like charm.
Ok, tried same way as CI does to serch:
transaction site:http://laravel.com/api/
then it finds. If there is no other way, maybe I should bookmark the search link and just change the keyword or something like that.
CodeIgniter was definitely simpler, to the point that any larger project suffered greatly under the weight of (forcibly) badly misplaced code. Laravel raises the bar there a little bit, but it's to your benefit as a developer (I promise :D ).
Firstly, kudos for searching through the code. Many people do not. You learn a LOT by looking in there.
Laravel Code
For Laravel, you'll do best by knowing about Namespaces, and how they relate to autoloading files (Namespaces will relate to directories, essentially). You likely know this, but it relates to how you can find classes and their methods.
Now, this doesn't go towards knowing where anything is - that comes with some digging into the code yourself. I almost always have Github open to the laravel/framework repository to look at code.
Note: That API search looks for files, rather than methods within them (unfortunately).
Github
As mentioned, I use Github mercilessly for searching code, instead of the API documentation. The search in Github is quite good - it will search within the current repository.
For example, I searched "function transaction" in github and got good results.
It led me to see here that it accepts a closure, and surrounds the code run within the closure around a transaction. You can see that throwing any exception within that closure will get caught and cancel the transaction (and gives you a way to control it).
Facades
As #matit pointed out, Facades do in fact hide where code is. That's a tricky part. In general, you can call the getFacadeRoot() method on any facade to figure out what class it is:
// Figure out what underlying class the Auth facade actually is
echo get_class( Auth::getFacadeRoot() );
Eventually you'll discover patterns in the code. Most facades point towards certain types of classes within each package (For instance, a Manager class who's job it is to decide which underlying implementation is used).
I really suggest reading Taylor's book which goes into the general architecture of Laravel. It's a quick read which is highly worth it.
Where CodeIgniter excelled in simplicity, Laravel excels in teaching you better coding concepts. Give it some time :D (Or use CodeIgniter still, that's cool too - whatever gets your work done!)
This is why I strongly suggest using CTAGS! I use sublime text 2 with the CTAGS plugin. I just press CTRL+SHIFT+Click on the class method and it will bring up a list of classes that have that method, or if only one exists, take me directly to the file and method. It beats searching the API/docs in terms of speed. There is even a Sublime text 2 plugin for Laravel Facades !
https://github.com/stidges/Laravel-Facades-for-ST

Resources