Einträge mit Label anzeigen: laravel. Zeige alle Artikel.

Apparently Google doesn't like it if all of your pages have the same title and meta description tags. So yesterday I decided to write unique titles and description tags for all of my pages. At first I did this by setting two variables - $title and $description - in my controllers and then passing them to the views, where I displayed them in my layout/app.blade.php. Since I have multiple languages in this site I ended up setting them like this:

$title = trans('whatever.pagetitle');
$description = trans('whatever.pagedescription');

This seemed a bit inelegant and I thought I could come up with a better way, which I did this morning. What I did was set up a file in my lang directory I called metadata.php. A sample of this is here. This file contains for each page a key for title and description as follows:

'/home-title' => 'Title';
'/home-description' => 'Description';

By using the URI appended with the value I want I was able to consolidate all of the values into one file for ease of use, and I was also able to make a helper function to get those values from the translation files and display it, so that the same exact code could be run on every single page and return the data I need. 

The helper function I used is on my GitHub here, and if it doesn't find data for the page it is looking for it has a default title and description it uses. For pages like blog articles and individual records I use the same title and description, but I still specify $title in the Controller, and if the value exists it is appended to the title in the layout file.

I like this solution because it allowed me to delete the redundant and ugly code in the controllers where I specified a title and description for each page with a function that pulls the data from one location, and if the data doesn't exist it substitutes a default in, instead of either failing or not doing anything. The code I used is on my GitHub Gist.

Etiketten: coding, laravel
Keine Kommentare

Laravel Blog Package

Sonntag 08 Januar 2017

I finished working on my Laravel package, which is the blog I use here (and also on my other site). I had this on my GitHub as a Laravel skeleton application, but after a few days of research and coding I now have it as a Laravel package, which can be installed via Composer. I did find a more comprehensive tutorial on writing Laravel packages, but I only just found this today after I had finished my package, so haven't really read through it.

The reason I started working on this package is because I have multiple sites that use the same code and I wanted to consolidate them so I wouldn't have to maintain two separate code bases, but the package is only in English and some of my sites are in French, so I guess my next step is adding translation to the package.

The package is on Packagist and can be installed with composer. 

composer require escuccim/larablog

A few things that I struggled with and eventually figured out since my last post on this topic:

  • How to publish files from the package to the containing application. I did this for both my views and the config.php file.

    $this->publishes([

    __DIR__.'/config/config.php' => config_path('blog.php'),

    __DIR__ . '/resources/views' => base_path('resources/views/vendor/escuccim')

             ]);

  • To default to the package config if it has not been published use:

    $this->mergeConfigFrom(__DIR__.'/config/config.php', 'blog'); where 'blog' is the key for the config array.

  • How to load database migrations:

     $this->loadMigrationsFrom(__DIR__.'/database/migrations');

  • I also updated the code so that things like caching could be turned on and off from the config. 

There is still work to be done, but I just marked my GitHub repo with a stable release version, so that's something.

Etiketten: coding, laravel
Keine Kommentare

Laravel Packages

Donnerstag 05 Januar 2017

I've been trying to figure out how to make packages for Laravel, and there isn't as much documentation as one would hope there is. The Laravel docs aren't as helpful as they could be for someone who has never done this before, and most of the info I found on Google was either incomplete or for older versions of Laravel.

I did find a few pages with helpful information on how to do this, this one is the one I followed. It uses this CLI tool, itself a Laravel package, which will allow you to make other Laravel packages. The CLI tool creates the directory structure along with composer.json and boilerplate code that provides a good starting point.

Other tutorials I found helpful include:

 I ran into a few problems which took some research to solve, which I thought I'd put here in case anyone else is having the same issues:

  • If you are getting an error that the service provider you created can't be found check the capitalization of the autoload in your composer.json file and make sure it matches the entry in the providers array in config/app.php. I had this problem when I first started working on my package, and then I decided to rename the package and ran into the same problem again.
  • Views - if your package has it's own views you can load them from the controller as "[vendorname]::[dir]/[view]", where [vendorname] is the vendor name of your package, which you should be creating in the register function in the service provider file.
  • Creating URLs in views - my views used action() to create the URLs and when I moved my controllers out my App directory all my links broke. I've tried using the full path to the controllers in my package couldn't get it to work so ended up replacing them all with url().
  • Using Models in your package - I created a directory under my package src/ called Models and I put all my Models in there. Make sure you change the namespace and update any use statements that reference the old location.

Of course I had other issues but those are the ones that took a while to figure out. I hope to finish the package up in the next few days, I'll post updates as they come.

Update - to use action() to create URLs you in fact do use the full path to the controller and it works this time. Not sure what I did wrong last time, but it is working fine now.

Etiketten: coding, laravel
1 Kommentare

Laravel Localization

Sonntag 18 Dezember 2016

I decided to try to translate this site into French, given that I live in the French-speaking part of Switzerland. Laravel has a lot of great tools for localization built-in, but there were a few things sorely lacking. Laravel, by default, has localization files in /resources/lang/en. Each file is just an array with a key and the translated text as the value. If you want to add a new language you just copy the files over into a new directory, in this case /fr, and translate the text directly in there. In the views instead of typing in the text directly you call trans('file.key') and it pulls the text for 'key' out of the 'file.php' in the appropriate language directory. This couldn't be any easier.

The hard part was when I started trying to figure out how to set the language to be displayed automatically. Laravel pulls this value from config/app.php, and you can change this value easily, but because Laravel is RESTful it has to be done on every request. So I decided to stick the actual language in a session variable and then change the value in the config array if needed.

I tried to make a middleware to do this on each request, but this didn't work because it seemed as if the session either wasn't saving from middleware, or possibly wasn't initialized yet in the middleware. More on this below. So I abandoned the middleware route and added a function in my controller that sets the language thusly:

App::setLocale( session('locale') ? session('locale') : config('app.locale'));

This worked fine, I just need to make sure to call the function everytime a page may need to be translated. My next step was to try to add a subdomain 'fr.' that would automatically set the language to French. You can do this in the web.php routes file, but from what I can tell it needs to be called on every single route, which seemed like an awful lot of work for something that should be pretty easy. 

So I went back to the middleware and created a middleware called SetLanguage that I added to app\Http\Kernel.php so it runs on every request. The middleware is quite simply this:

$pieces = explode('.', $request->getHost());
if($pieces[0] == 'fr'){
    session(['locale' => 'fr']);
}
return $next($request);

And this works fine. I think the problems I had with the middleware the first time I tried it was that Laravel has changed how sessions are handled in new releases, and the Session facade no longer works or works differently. Instead you now use the session() helper function or call $request->session() to modify the session. I had been trying to use the Session facade.

One thing that seems a bit odd is that since the middleware runs on every request it should translate every page that is called from the fr. subdomain to French. In actuallity it initially sets the language to French, but if you change the language using the drop-down menu it keeps the selection. This doesn't seem right, but in this case the actual behavior makes more sense than the expected behavior, so I am ignoring this bug.

Once I got this figured out, the translation was a simple matter of replacing text in my views with references to the lang files, which went smoothly, although I did have to spend some time trying to figure out how to translate some technical terms into French, and still am not sure I have them all translated properly.  

Etiketten: coding, laravel, localization
Keine Kommentare

Laravel Pagination and Ajax

Montag 24 Oktober 2016

I just updated the search of my records here so it would load the results using Ajax instead of refreshing the whole page. Everything seemed to work fine, but then I noticed that it broke the Laravel pagination. I included the pagination in the section of the page reloaded by searches and sorts so it would update appropriately, but then the page links just loaded the results and didn't load the results into the div on the page where they were supposed to be.

This was a bit tricky to solve. What I ended up doing was exporting the pagination views to my resources directory, and then editing it there. To each of the pagination links I added two things:

  • class="page-link"
  • data-val="{ number of page to be loaded}"

Then I added a script to the page that triggers when you click an object with the class of page-link, that gets the page to be loaded from the data-val attribute and submits that to the script that loads the appropriate page with the appropriate variables. Then I did the same thing for the sort links - instead of having each trigger it's own script I made one script triggered by a click on the class and put the data in the data-val.

Etiketten: coding, laravel
Keine Kommentare

Archiv