Passing data to view in laravel - laravel

I have the following code
$input = Input::all();
$this->agro->create($input);
$alldata = $this->agro->all();
return View::make('agro.showdata',['myalldata'=>$alldata]);
Here when I return $alldata, all data from database is displayed.I guess here all the data is stored in $alldata variable which we are passing to the showdata view file in the variable myalldata.
Now when in myalldata, if data is not accesses it works as
<h1>DIsplaying data </h1>
But when I try to display data, it gives error Whoops, looks like something went wrong
ie
<h1>Displaying data from database<h1>
{{ $myalldata->title }}
Please help display the data from database.
Another thing, every time something is wrong, it gives error Whoops, looks like something went wrong.How to debug laravel to know where things are going wrong?

It appears that $myalldata is an array of elements. To access each one, you'd need to use a for-loop, like such, in your view:
#foreach($myalldata as $row)
<div>{{{ $row->title }}}</div>
#endforeach
You can determine whether to display the full error trace by modifying your application's app/config/app.php file, and replacing
'debug' => false,
with
'debug' => true,
Keep in mind that, in a production environment (when clients can access the site), you'll want to disable debug mode.

How to debug laravel to know where things are going wrong?
Go to your config/app.php or config/yourEnvironment/app.php and set Application Debug Mode to true.
'debug' => true,

Related

View::make in Phpunit

I've a function that returns a View::make($string). I want to test that this function did indeed return an instance of View object. $string points to a file that does exist.
When I try to run this function within Phpunit it doesn't seem to finish. How can I test in Phpunit that a View object was created?
Laravel has helper methods specifically designed for testing views.
Some of them include:
$response = $this->get('/path/to-your-route');
$response->assertViewIs($value);
$response->assertViewHas($key, $value = null);
$response->assertViewHasAll(array $data);
$response->assertViewMissing($key);
More info can be found here: https://laravel.com/docs/5.5/http-tests#available-assertions
If you need to assert that something is an instance of something else, you can try the following:
$this->assertInstanceOf($expected, $actual);
When you provide invalid string the view object will not be created and will throw an exception. Not sure what you have in your function that prevents the exception, but the way to go around this issue, is to include this line in the failing test:
$this->expectException(InvalidArgumentException::class);
The issue stemmed down from usage of var_dump as I wanted to see the object in question. As nothing was presented in output, I assumed that had to do with View::make rather than outputting the object to the console.

Executing Artisan command with arguments

Currently i'm facing following problem:
I want to update my search index automatically after my database has been updated.
I've registered a saved() listener on my tables in AppServiceProvider:
\App\Customer::saved(function(\App\Customer $customer) {
// Update search index here
});
Inside the closure i try to call an Artisan command (scout:import) passing App\\Customer to the command. I've tried
Artisan::queue('scout:import', ['' => 'App\\\Customer']);
// Fails with message: Uninitialized string offset: 0
Artisan::queue('scout:import', ['model' => 'App\\\Customer']);
// Fails: Cannot redeclare class App\Customer
Artisan::queue('scout:import', ['App\\\Customer']);
// Fails: Not enough arguments (missing: "model")
I did'nt find information where to put the required arguments in the offical documentation.
I'm sure that it's dead simple (like everything in laravel) but i'm not able to get it done ...
The correct format is:
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
As per: https://laravel.com/docs/5.3/artisan#programmatically-executing-commands
I'd say your middle example is probably closest, and is executing the command with the correct parameters, but there is something else going on under the surface.
EDIT
Just did a bit more digging, you need to refer to the signature of the Console command, which isn't actually apparent on the surface. In your case, you need to refer to this console command:
https://github.com/laravel/scout/blob/2.0/src/Console/ImportCommand.php
Note the signature is marked with {model}.
So your command would look like:
Artisan::queue('scout:import', ['model' => 'App\\\Customer']);
Another example using the controller make command, note that this time we using the signature segment {name}:
Artisan::call('make:controller', ['name'=>'FOOBAR']);
Again, there is probably an underlying issue here - you should try running the import command from the console/terminal directly to see if you get the same issue.
Try this:
\App\Customer::saved(function(\App\Customer $customer, $input) {
// Update search index here
});
Artisan::queue('scout:import {input}', ['App\\\Customer']);
You don't need to sync with algolia using an artisan call.
Refer to algolia documentation:
Algolia Laravel Doc
'Every time you modify a model, Laravel emits an event. Scout is listening for that event, informing your app to make an HTTP call to Algolia to update its index.
You don’t have anything else to do, use your searchable class the way you usually would do'

How to increase CakePHP Debugger maximum depth

I'm trying to debug my program by logging information from an ajax call. This is something that doesn't render a view, just runs asynchronously. The log will only display arrays to a depth of 3, and the documentation doesn't seem to have any notion that someone might want more information than that.
Please, how do I increase this depth so I can have access to this information without finding weird ways to render my ajax call? Or, if doing this isn't the "Cake" way, is there a better way to output info to a log or console for debugging?
I think this is not the case of CakePHP but an issue with XDebug or PHP configuration itself. You can try to add this line to your php.ini
xdebug.var_display_max_depth = 5
It works if you debug with var_dump(). You should write how do you try to debug, bacause different methods depends on different mechanisms.
If it doesn't work you can try to make the Cake to display original PHP error messages instead of its own error handler messages. In your core.php find code like this:
Configure::write('Error', array(
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
And change it into this:
Configure::write('Error', array(
//'handler' => 'ErrorHandler::handleError',
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
and add this line at the end of bootstrap.php :
function displayErrorWithoutCrap() {
return false;
}
I ended up submitting a ticket to the Git project for CakePHP and it was confirmed that the debug depth for arrays is hard-coded for log files. The response indicated that it would be considered for a change in the next version.
I ended up finding the number in the Debug class and changed it to a larger number which gave me more depth. Not the best fix, but it works for now until support is added to the next version.

Joomla >1.7 hide log messages from browser

I'm developing an extension for Joomla!; at the moment I'm trying to make it 3.0 compatible - as with 3.0 the logging changed a little (*). Building on the answer from this related question, my current code looks like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php'
));
JLog::add('blah blah log msg');
The problem is that the log also goes to the messages which are shown to the user - this I want to prevent, I want the log msg only to go to the log file. I think it has to do with the "category" that JLog::add takes as a 3rd (optional) parameter, but I have no idea what to pass there?
Can anybody tell me how to hide the messages / or tell me if I'm on the right way with the categories and what value I should use?
Thanks!
(*) It actually changed already with 1.7 as far as I gathered so far, but the old method of calling addEntry on the return of JLog::getInstance(...) seems to have been removed from 2.5 to 3.0.
Edit: Think I found a way now; using:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
'myplg'
));
JLog::add('blah blah log msg', JLog::INFO, 'myplg');
all my log entries go only into my log file (and not to the messages shown to the user). However, I also get a few deprecation warnings - one about my code, but also some unrelated ones:
WARNING deprecated JAccess::getActions is deprecated. Use JAccess::getActionsFromFile or JAcces::getActionsFromData instead.
WARNING deprecated JSubMenuHelper::getEntries() is deprecated. Use JHtmlSidebar::getEntries() instead.
WARNING deprecated JSubMenuHelper::getFilters() is deprecated. Use JHtmlSidebar::getFilters() instead.
WARNING deprecated JSubMenuHelper::getAction() is deprecated. Use JHtmlSidebar::getAction() instead.
Not sure what to make of those - why do they appear in my log file, shouldn't they go to the default error.log file instead of my file ?
This is what I am using, works for Joomla 1.5 - 3.2:
if(version_compare(JVERSION,'1.7.0','ge')) {
jimport('joomla.log.log'); // Include the log library (J1.7+)
$priorities = JLog::ALL ^ JLog::WARNING; // exclude warning (because of deprecated)
// In J3.0 we need to ensure that log messages only go to our file, thus use the categories (already supported in J2.5)
if(version_compare(JVERSION,'2.5.0','ge')) {
$logCategory = 'com_mycomponent';
JLog::addLogger(array('text_file' => $logFileName), $priorities, $logCategory);
JLog::add($msg, JLog::INFO, $logCategory);
}else{
JLog::addLogger(array('text_file' => $logFileName), $priorities);
JLog::add($msg, JLog::INFO);
}
} else {
// Joomla! 1.6 and 1.5
jimport('joomla.error.log'); // Include the log library
$log = &JLog::getInstance($logFileName);
$log->addEntry(array('comment' => $msg, 'level' => 'INFO'));
}
This shows the trick for gettring of the deprecated messages.
And yes, you have to include a category for your messages to ensure they are not showing up as system messages.
Use
new JException('Something happened');
This will only add it to debug log but will not show anything.
It seems, that Joomla 3.0 has no default logger enabled. The same in Joomla 3.0.3. Nothing turns logging on by default - even Debug mode.
Finally I think I have solved my issue with unrelated log entries showing up.
A close look at the API documentation of the addLogger function revealed that the third parameter, $categories, is supposed to be an array of categories for which this log will be used.
This is in contradiction to the version of http://docs.joomla.org/Using_JLog that is current at the time of this writing, where a single category is given instead of an array.
Changing my call to addLogger to use an array, like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
array('myplg')
));
And keeping my fingers crossed that this will fix the issue!
Edit: unfortunately even this still doesn't solve my issue - still got unrelated entries :(.
I found the answer.. hope this script make you understand.. I already built as function . this code work on joomla 3. hope work in joomla 2
<?php
function logWrite($level, $values, $file='%s.php',$path='',$showOnTop=0,
$option='',$component=''){
/****
jlog Joomla 3.4
created by:gundambison (2015.04.26).
THX: hbit#stackoverflow
****/
jimport('joomla.log.log');
$level=strtoupper($level);
//You can change this com_name
$component= $component==''? 'com_gundambison': $component;
$date= date("Ymd");
$filename= sprintf($file, $date);
$format= $option=='' ?"{TIME}\t{CLIENTIP}\t{CATEGORY}\t{MESSAGE}": $option;
// create options and text
$txt = is_array($values)? json_encode($values): $values;
$options = array('text_file' => $filename,'text_entry_format'=>$format );
$options['text_file_path']=$path==''?'logs': $path;
JLog::addLogger ($options);
/*
if you want the error to show in your page. just see the different
*/
if($showOnTop==1){
JLog::add("$txt");
}
else{
JLog::add("$level\t$txt",$level,$component);
}
}

Implementing Database Error Handling in CodeIgniter

I am creating a webapp using codeigniter. I want to implement a error handling function. Say for example if I call a method of a model, and if an error occurs in that method, the error handler comes into action to return some pre-formatted string.
I was thinking of creating something like MY_Model, which every model class extends. Then, I can add the error handler in MY_Model class. But whether this can be done is beyond me right now. (yes I am a newbie at this)
Any enlightening ideas will help.
Regards
What I tend to do is return an array instead of a boolean. This array contains 2 keys, 'return' and 'error'.
In case of an error this array will look like the following:
array('return' => FALSE, 'error' => 'Some error')
In case of a successful execution this array will look like the following:
array('return' => TRUE)
The controller then verifies these results and if there's an error it will display the one set in the 'error' key.

Resources