I have this code below from my old Laravel 4.x. How can I convert this into Laravel 5.1? I am wondering how can I access the route params in the constructor(or in a middleware) if I convert it to Laravel 5.1
thanks!
public function __construct()
{
$this->beforeFilter(function($route, $request)
{
$this->user = Auth::user();
$this->project = $this->user->getProject( $route->parameter('projects') );
$this->group = $this->project->groups()->find( $route->parameter('groups') );
});
}
I hope someone will be helped by this:
$request->route('companies')
Related
I'm trying to add localization support for a card built for the Laravel Nova dashboard.
I already created a folder in /resources/lang containing the JSON language files in a format like en.json. The files get published (copied) with the publish command but the loadJsonTranslationsFrom() does not seem to do anything:
class CardServiceProvider extends ServiceProvider
{
public function boot()
{
$this->publishes(
[__DIR__ . '/../resources/lang' => resource_path('lang/vendor/my-custom-card')],
'my-custom-card-lang'
);
$this->loadJsonTranslationsFrom(resource_path('lang/vendor/my-custom-card'));
}
}
This is how the markup in Card.vue looks like:
{{__('Title')}}
How can I test if the JSON files are loaded correctly? What am I missing?
The question is how do I support localization for cards in Laravel Nova?
Card localization has been solved in Laravel Nova 2.
To localize strings use the __ helper within your Vue components and load the according translation files within your NovaServiceProvider:
Nova::serving(function (ServingNova $event) {
Nova::script('{{ component }}', __DIR__.'/../dist/js/card.js');
Nova::style('{{ component }}', __DIR__.'/../dist/css/card.css');
Nova::translations(__DIR__.'/../resources/lang/en/card.json');
});
An exemplary implementation can be found on GitHub.
Further information is now available in the documentation.
I'm having the same issue, but for a tool, also in Nova 2.0.
I found a somewhat elegant solution - maybe it helps someone nonetheless.
Create en.json in /nova-components/{your-tool}/resources/lang/
In /nova-components/{your-tool}/resources/js/tool.js add Vue.mixin(require('./translation'));.
It should look something like this:
Nova.booting((Vue, router, store) => {
router.addRoutes([
{your-routes}
]);
Vue.mixin(require('./translation')); <-------------- add this line!
});
Create the /nova-components/{your-tool}/resources/js/translation.js, it should look like this:
module.exports = {
methods: {
__(key, replace) {
var translations = _.merge(window.config.translations, window.config['tool-translations']);
var translation = translations[key]
? translations[key]
: key;
_.forEach(replace, (value, key) => {
translation = translation.replace(':' + key, value)
});
return translation;
}
}
};
Now you have to add the following to the Nova::serving() function inside the boot() function of your /nova-components/{your-tool}/src/ToolServicePrivoder.php file:
Nova::provideToScript([
'tool-translations' => $this->getTranslations(),
]);
Now add below said boot() function the following:
private static function getTranslations()
{
$translationFile = __DIR__ . '/../resources/lang/' . app()->getLocale() . '.json';
if (!is_readable($translationFile)) {
return [];
}
return json_decode(file_get_contents($translationFile), true);
}
I have added OData V4 to my Web Api 2 app.
registered OData route in WebApiConfig register method before default route:
//defining the routes for our OData service
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: GenerateEdmModel());
private static IEdmModel GenerateEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Media>("Media");
return builder.GetEdmModel();
}
MediaController.cs
[EnableQuery]
public IQueryable<ApiMedia> GetMedia(ODataQueryOptions<Media> query )
{
*querying and returning media*
}
but when I call localhost:80880/odata/media
returned response says:
The resource cannot be found.
Requested URL: /odata/media
calling localhost:80880/odata returns this:
{
"#odata.context":"http://localhost:80880/odata/$metadata","value":[
{
"name":"Media","kind":"EntitySet","url":"Media"
}
]
}
so whats wrong here?
(does it looking for a controller named odata?)
I followed the tutorial on http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint
you cant believe but I should type mysite.com/odata/Media not mysite.com/odata/media
You will quickly find this feature. I was looking for 2 days. Uppercase url request depends on the entityset name
builder.EntitySet<Media>("Media"); // if the changed to "media" will work !
Hi i started learning ZF2 a week ago and i am facing some issues in how to work with session in ZF2.
namespace MyApplication\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container; // We need this when using sessions
class UserController extends AbstractActionController {
public function loginAction() {
$user_session = new Container('user');
$user_session->username = 'bravo';
}
public function welcomeAction() {
$user_session = new Container('user');
$username = $user_session->username; // $username now contains 'bravo'
}
}
Can anyone please help me with the exact code snippet or tell me where i am wrong.
Thanks in advance :)
I am also not much familiar to ZF2 but my code may solve the issue you are facing.
class UserController extends AbstractActionController {
public function loginAction() {
// Store username in session
$user_session = new Container('user');
$user_session->username = 'bravo';
return $this->redirect()->toRoute('welcome');
}
The issue was in the function named loginAction you have not redirected after creating the session
Hope it helps you
i am following a getting started tutorial on zend framework 2, in one of the topics it suggests using tests, the code it suggests is:
namespace ApplicationTest\Controller;
use ApplicationTest\Bootstrap;
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use PHPUnit_Framework_TestCase;
class IndexControllerTest extends PHPUnit_Framework_TestCase
{
protected $controller;
protected $request;
protected $response;
protected $routeMatch;
protected $event;
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new IndexController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
public function testIndexActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'index');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
}
as you can see there is no __autoload($class).
to manually make it work i added include "../../Bootstrap.php"; it did solve the problem but i remember once i could get this code to work, and the tutorial doesn't seem to forget something conceptually obvious and there is no feedback about it in the Topic comments , there may be something I am missing, how would the code above probably work?
I managed to get it working but noticed you couldn't use phpUnit's extended Request and Response objects. These are the instructions for early 2.0 release. At least after 2.0.7, the instructions are much different and the code is cleaner:
http://zf2.readthedocs.org/en/latest/user-guide/unit-testing.html
<?php
namespace ApplicationTest\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class IndexControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include '/path/to/application/config/test/application.config.php'
);
parent::setUp();
}
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/');
$this->assertResponseStatusCode(200);
$this->assertModuleName('application');
$this->assertControllerName('application_index');
$this->assertControllerClass('IndexController');
$this->assertMatchedRouteName('home');
}
}
In this example testing is carried out by extending Zend's controller test case, which was the way controller tests were carried out with zf1.
In symfony, I call an action and I want this to return json to jQuery frontend.
The Jobeet tutorial teaches how to return a partial but I want to return json, not a partial.
If it's just a normal AJAX action you're returning it from, I think I've used the following somewhere in the past:
return $this->renderText(json_encode($something));
The cheap way:
function executeSomethingThatReturnsJson(){
$M = new Model();
$stuff = $M->getStuff();
echo json_encode($stuff);
die(); //don't do any view stuff
}
The smarter way:
A smarter way is to create a nice subclass of sfActions that helps handling json-stuff.
In a project I did recently, I created a application called 'api' (./symfony generate:application api)
and then created a file like:
api/lib/apiActions.class.php
<?PHP
class apiActions extends sfActions {
public function returnJson($data){
$this->data = $data;
if (sfConfig::get('sf_environment') == 'dev' && !$this->getRequest()->isXmlHttpRequest()){
$this->setLayout('json_debug');
$this->setTemplate('json_debug','main');
}else{
$this->getResponse()->setHttpHeader('Content-type','application/json');
$this->setLayout('json');
$this->setTemplate('json','main');
}
}
}
Notice that I explicitly set the template there.
So my jsonSuccess.php template is simply:
<?PHP echo json_encode($data);
While json_debugSuccess.php makes things prettier:
<?PHP var_dump($data); ?>
Then you can have a controller that extends apiActions (instead of the usual sfActions) that looks like this:
<?php
class myActions extends apiAction {
public function executeList(sfWebRequest $request)
{
$params = array();
if ($request->hasParameter('id')){
$id = $request->getParameter('id');
if (is_numeric($id)){
$params['id'] = $id;
}
}
$data = Doctrine::getTable('SomeTable')->findAll();
$this->returnJson($data);
}
}
Disclaimer: The code above is copy/pasted out of an app I have, but simplified. It's for illustrative purposes only -- but it should get you heading in the right direction.
FYI: In case of Symfony 2.x "quick and dirty" way looks like this:
return new Response(json_encode($data), 200, array('Content-Type', 'text/json'));
Return new JsonResponse(array);