with() and leftjoin() in Laravel - laravel-5.5

How can I use both with() and leftjoin() in Laravel eloquent? I would like to use in below code.
$applicants = Applicant::with('applicant_skill')->paginate();

You can use whereHas
$query = Applicant::whereHas('applicant_skill', function ($q) {
$q->where('name', 'PHP');
})
->paginate(10);

Related

Scriban function to convert snake case to pascal/camel case

I'm trying to generate some C# code using Scriban templates. The DB I'm using is postgresql, so my tables and properties are all in snake_case. I managed to make a function to convert snake case to pascal case:
{{ for word in EntityName | string.split "_" -}} {{~word | string.capitalize}} {{-end}}
This does convert entity_name to the desired EntityName.
And camel case:
{{func split(en)
ret en | string.split "_"
end}}
{{for index in 0..#split(EntityName).size -}}
{{-if index == 0}} {{~#split(EntityName)[index]-}} {{-else-}} {{-#split(EntityName)[index] | string.capitalize-}} {{-end-}}
{{-end}}
However, I need to use this function multiple times in my template, therefore I wanted to make a function I can use throughout the template, just like the split(en) function I use for the camel case conversion. So I could do something like this everywhere I need it:
{{ #convert(EntityName) }}
Is this possible, and if yes, how?
Any help would be appreciated!
I found another solution to my problem. Instead of creating functions in the template itself, I make a ScriptObject.
public class ScribanHelper : ScriptObject
{
public static string ConvertToPascalCase(string word)
{
if (string.IsNullOrEmpty(word))
return string.Empty;
return string.Join("", word.Split('_')
.Select(w => w.Trim())
.Where(w => w.Length > 0)
.Select(w => w.Substring(0, 1).ToUpper() + w.Substring(1).ToLower()));
}
}
And then I push this to the scriban context to use it in the templates.
var context = new TemplateContext { MemberRenamer = member => member.Name };
var scriptObject = new ScribanHelper();
context.PushGlobal(scriptObject);
var templateString = File.ReadAllText(templateSetting.Name);
var template = Template.Parse(templateString);
var entityScriptObject = new ScriptObject();
entityScriptObject.Import(entity, renamer: member => member.Name);
context.PushGlobal(entityScriptObject);
var result = template.Render(context);
And then I can easily use it in the templates.
{{-func pc(name)
ret convert_to_pascal_case name
end}}
{{#pc(EntityName)}}
You can try this https://github.com/Humanizr/Humanizer. You still need to create the function and can use word.Pascalize() inside it.

Unite Test: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

I'm trying to write white test to test my API with file uploads.
I'm following the docs about this using basic client request, not crawler.
The unit test is:
class RecordsControllerTest extends WebTestCase {
private $client;
public function __construct() {
parent::__construct();
$this->client = self::createClient();
$this->client->insulate();
}
public function testApiPostUpload($params){
$fileToUpload = realpath(__DIR__.'/../../resources/mpthreetest.mp3');
$file = new UploadedFile(
$fileToUpload,
'mpthreetest.mp3',
MimeTypeGuesser::getInstance()->guess($fileToUpload),
filesize($fileToUpload)
);
$this->client->request('POST', '/records/'.$params['createdRecordId'].'/upload', array(), array('file' => $file) );
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
When I execute the test I receive an error:
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:165
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:348
/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:143
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:313
/path/to/project/src/Bundle/Tests/Functional/Controller/RecordsControllerTest.php:182
I have found this question for about the same error, but in this case the request is not sent to the controller and the problem is not the entity and implementing serialization.
Anyone who knows how to fix this?
Anyone who managed to make unit test for uploading file in symfony 2?
You could try to NOT insulate the requests passing false as argument to the insulate method so try this:
$this->client->insulate(false);
instead of this:
$this->client->insulate();
Hope this help
I was able to resolve it by setting the changeHistory parameter to false (7th and last parameter in the request method signature):
$crawler = $client->request($form->getMethod(), $form->getUri(), $values, $files, [], null, false);
This will prevent the serialize on following lines :
if ($this->followRedirects && $this->redirect) {
$this->redirects[serialize($this->history->current())] = true;
return $this->crawler = $this->followRedirect();
}

Request in PhpUnit using Laravel 5.1

I'm testing my Rest APIs.
I want to pass a parameter to my request.
This is in my controller, I have:
public function index(Request $request)
{
$abuse = Abuse::where('bombId', $request->input('bombId'))->get();
}
Thing is with PhpUnit, I can never simulate the bombId parameter...
Here is my code:
$data['bombId'] = 25; // I also tried $bombId = 25;
$this->get('api/v1/abuse', $data])
->seeJson(['total' => 11]);
$this->assertResponseStatus(200);
EDIT:
When I use:
$this->call('GET','api/v1/abuse', $credentials);
Param is passed, but I can't use anymore SeeJson method :(
Any Idea?
I found my answer with Jeffrey Way:
$response = $this->call('GET', 'api/v1/abuse', $credentials);
$data = $this->parseJson($response);
$this->assertIsJson($data);
$this->assertEquals(11, $data->total);

Get Returned text from ScriptManager(javascript) - INDESIGN SDK Plugin

I am using javascript inside my Plugin for Indesign CS6.
It is working fine.
But I need the return value from my javascript code now inside my c++ code.
I am using this site as reference:
https://blogs.adobe.com/indesignsdk/running-a-script-from-an-indesign- plug-in/
I need something like that:
scriptRunner->RunScript("function xpto(){return 'Hello World';};xpto()", params);
// fake method
const char *string_return = scriptRunner->getReturnCode();
are there something like that on scriptManager?
ps: it is not a indesign server. I put this tag because this site do not let me create a new tag...
Best Regards,
Use RunScriptParams::QueryScriptRequestData() .
From the SDK documents:
Query the IScriptRequestData that is used to pass arguments and return
the result.
The key is to get the iScript object from the 'RunScriptParams' object after the script has run. Then is it straight forward. Here is some sample code:
RunScriptParams params(scriptRunner);
IScriptRequestData* requestData = params.QueryScriptRequestData();
params.SetUndoMode(RunScriptParams::kFastUndoEntireScript);
if (scriptRunner->RunScript(script,params) != kSuccess) return NULL;
IScript *iScript = params.QueryTarget();
int resultsCount = requestData->GetNumReturnData(iScript);
PMString resultString;
if (resultsCount > 0) {
ScriptReturnData resultOne = requestData->GetNthReturnData(iScript,0);
ScriptData scriptReturnOne = resultOne.GetReturnValue();
scriptReturnOne.GetPMString(resultString);
}
The return value is in resultString.

AngularJS : Stubbing JQlite methods

I'd like to unit test some logic in my directive :
...
link: function ($scope, $element) {
var rightMargin = 3;
var w = $element.find('span')[0].scrollWidth;
if (w > 100) {
$element.css('width', (w + rightMargin) + 'px');
}
...
Because the $compile service doesn't really add elements on document, scrollWidth always returns 0.
So I don't know how to stub the returned value of $element.find call because there is no way to access $element instance in my unit test.
Try setting the HTML of the page directly inside of body
Using innerHTML:
angular.element(document.body).html('<div class="my-elm" my-directive></div>');
var elm = angular.element(document.body.querySelector('.my-elm'));
$compile(elm)($rootScope);
Or using append:
var elm = angular.element('<div class="my-elm" my-directive></div>');
angular.element(document.body).append(elm);
$compile(elm)($rootScope);
If this is a unit test, then you shouldn't be testing the external dependencies, only that you're logic is accurate. I'd stub it out like.
spyOn($element,'css');
#call your code here
expect($element.css).toHaveBeenCalledWith('width','99px');