Relationship is working in Laravel Tinker but not within controller - php

I made a manyToMany relationship and want to return that in my php code which is not working, but when I run the same code in tinker it is working for some reason. What am I missing?
// Firma
public function auftraege()
{
return $this->belongsToMany("Auftrag", 'auftraege_firma');
}
// Auftrag
public function firmen()
{
return $this->belongsToMany("Firma", 'auftraege_firma');
}
// works in tinker
$firma = App\Firma::first();
$firma->auftraege
// Does not work in php Controller
$firma = App\Firma::first();
return $firma->auftraege
Getting 500 Error

Looking at your controller code, I can only notice two things. Change your controller code like this:
$firma = \App\Firma::first();
return $firma->auftraege;
You are missing \ before the App namespace and also the semicolon is missing in the return statement.
Please also change the relationshps like this:
public function auftraege()
{
return $this->belongsToMany(Auftrag::class, 'auftraege_firma');
}
public function firmen()
{
return $this->belongsToMany(Firma::class, 'auftraege_firma');
}
The reason it was working from tinker is that by default tinker sets the namespace to App for the current tinker session. That's why even though you didn't specify the App namespace, tinker was able to parse the proper namespace.

Related

How to read config values in PHP controller?

I am using symfony 4.2 framework in which there is PHP controller with multiple actions. I have set below values in packages\config.yaml.
myDir: '/abc'
I have below controller with 2 actions as defined below.
//this works
public function uploadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
}
//this doesn't work
public function loadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
//$myDir = $r_request->query->get("myDir"); //this is also not working
}
Issue here is I am able to get the value in uploadTestAction but value is coming as null in uploadTestAction. I have tried using query as well but still not getting the correct value. Both request types are GET. What I am missing here or how can trace it ?
you should define it as parameter:
https://symfony.com/doc/current/service_container/parameters.html
final class XyController extends SymfonyController {
public function registerAction() {
$dir = $this->container->getParameter('dir');
}
}

Return value from one Artisan command to another

I am attempting to call one Artisan (Laravel) command from another command. However, I need to be able to retrieve an array from the command that is called from the "main" command...
i.e
// Command 1
public function handle() {
$returnedValue = $this->call( 'test:command' );
dump( $returnedValue ); // <-- is 5
}
// Command 2
public function handle() {
return $this->returnValue();
}
private function returnValue() {
$val = 5;
return $val;
}
I have looked through the documentation and can't find a way to do this, so I was wondering if there was a way or if I need to re-think my approach.
Thanks!
Artisan Commands don't behave the same way as, for example, Controller functions. They return an exitCode, which in my testing was always 0 (couldn't get anything to return if an error is thrown).
Your approach won't work if you try to get a return value, but you can access \Artisan::output(); to see what exactly is sent by the first artisan command you call.
// FirstCommand.php
public function handle(){
\Artisan::call("second:command");
if(\Artisan::output() == 1){
$this->info("This Worked");
} else {
$this->error("This Didn't Work");
}
}
Note: I used \Artisan::call(); there's some apparent differences between the two where using $this->call() didn't work as expected, but \Artisan::call() did. $this->call() sent both 0 and 1 back, regardless of the actual code being executed; not sure what's up there. Tested on Laravel 5.0, which is quite behind the current, so maybe that's it.
// SecondCommand.php
public function handle(){
try {
$test = 1 / 1;
} catch (\Exception $ex){
$this->error("0");
}
$this->info("1");
}
Running php artisan first:command in my console returns:
$ php artisan first:command
This Worked
Now, if switch the code in $test to
$test = 1 / 0;
I get this in my console:
$ php artisan first:command
This Didn't Work
So, the rule here I guess is to avoid outputting anything in the second command prior to the result you want to check with \Artisan::output().

get loggedIn user in View Composer not working(Sentinel - Laravel 5.4)

I am using Sentinel in Laravel 5.4. What I am trying to do is: get logged user detail but Sentinel::getUser() returns null. For this process, I have seen this instruction in this answer
. I am following using View Composer method.
Steps I have done
I have created a file ViewComposerServiceProvider inside Providers folder. It looks like:
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
view()->composer('backend.*', function($view) {
$view->with('userDetail', $userDetail);
//$view->with('userDetail', 'Test'); //this works fine
});
}
Then, I register this provider in config/app.php Providers array as
App\Providers\ViewComposerServiceProvider::class,
When, I pass other variables in userDetail, it's working perfectly. But, I cannot get the logged in user detail. Am I missing something?
Following the first solution from this answer also seems not working since, construct are run prior to the Middleware. Any help please.
Go to app\Providers\AppServiceProvider.php
Then your serviceProvider.php boot method like below
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
View::composer('userDetail', function($view) use($userDetail ) {
$view->with('userDetail ',$userDetail );
});
}
Then your userDetail.blade.php you can access userDetail data like this
{{ $userDetail }}

Why is the controller executed twice (flashbag, redirectoroute)?

I have two routes /alpha and /beta configured in yml. In alphaAction a notice is placed in the flashbag and a redirecttoroute occurs. In betaAction the notice in the flashbag is read.
Sometimes I get 2 notices when I try /alpha in the browser and sometimes I get one notice.
Can someone explain what is happening, what I'm doing wrong.
public function alphaAction()
{
$this->get('session')->getFlashBag()->add("notice",mt_rand());
return $this->redirectToRoute("beta");
}
public function betaAction()
{
$notices= $this->get('session')->getFlashBag()->get('notice');
return new Response(implode($notices,", "));
}
Using the add method I could reproduce the issues you described. This can be fixed by using the set method and not the add (or setFlash) method.
public function alphaAction()
{
$this->get('session')->getFlashBag()->set("notice",mt_rand());
return $this->redirectToRoute("beta");
}
public function betaAction()
{
$notices= $this->get('session')->getFlashBag()->get('notice');
return new Response(implode($notices,", "));
}

Build a UnitTest with multiple options on the same mocked-method

I have a problem to test a Method like that
public function index(){
if($this->request->is('get')){
if($this->Session->check('saveConflict')){
$this->set('conflict',true);
}else{
$this->set('data','test');
}
if($this->Session->check('full')){
$this->set('data',$this->Model->find('all'));
}else{
$this->set('data','test');
}
}else{
throw new BadRequestException;
}
}
unless that method maybe doesn't make sense, here is my problem. I have to call the method "check" on the Session-Component twice. But I want that for example the first methode mock-call retruns a "false" and the second a "true".
Here's what I have
$this->Editors->Session
->expects($this->once())
->method('check')
->will($this->returnValue(true));
I've tried it with the expectation "$this->at(1)" the call via order-index. But i think that isnt pretty clever because if I add a Session->check anywhere in the interpreted way though my base-method for example i have to change all those test-lines to make it work properly again.
I use CakePHP 2.4.6 and php-unit 4.1.3.
Is there any other why to do what I want to do?
Use the
->will($this->onConsecutiveCalls(array('return_value1',
'retur_value2',
...)));
Give the sequence of the return value in the order you want, the mocked method will return it in order.Or you can try the $this->returnCallback to do some sophisticated customize.You can find the example here How can I get PHPUnit MockObjects to return differernt values based on a parameter?.
Example
If you just want to do the unit test and cover all the path,I'll do like this:
public function testIndex()
{
....
$this->Editors->Session
->expects($this->any())
->method('check')
->will($this->returnCallback(array($this,'sessionCallback')));
$this->object->index();
$this->object->index();
.....
}
private $sessionFlag;
public function sessionCallback($value)
{
$rtnValue = $this->sessionFlag[$value];
$this->sessionFlag[$value] = (!$rtnValue);
return $rtnValue;
}

Categories