valentin vannay

valentincognito

Laravel 5 Useful Tips and notes

2016-03-23

Very often I find myself spending precious minutes going trough my messy handwritten notes and previous projects to find little block of codes I already struggled with. So I thought it was time to put everything in one place and also share it with whoever come across my little internet space ! So I'll update this post regularly with my most recent discoveries with Laravel and PHP in general. Note: all my notes are tested and used on laravel 5.2

Index

  1. Routes
    1. File download route
    2. Multi language website
  2. Controllers / Middleware
    1. Return view with data
  3. Eloquent ORM
    1. Many to many relationship process and queries
  4. Blade template
    1. Forms
   

1. Routes

1. File download route

Almost every time i need a route for client downloads on my websites. Here is the route:
Route::get('/download/{file}', function ($file) {
      return response()->download('uploads/'.$file);
});
And the download link:
<a href="{{ url('/download/document_name.extension') }}">Download</a>
 

2. Multi language website

There are a lot of different ways to deal with a multi language website, here is mine. First I create a group of route with a prefix for the local. With the below example you cannot access http://www.your-website/home anymore because it now requires a prefix in front of 'home' For example: http://www.your-website/en/home
Route::group(['prefix' => '{locale}'], function () {
			
// Your routes
    Route::get('home', 'HomeController@index');
});
And after that I create a middleware to handle this prefix and set the local accordingly.
<?php

namespace App\Http\Middleware;

use Closure;

class LocaleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app()->setLocale($request->locale);
        return $next($request);
    }
}
Then off course your menu links have to deal with the prefix:
<a href="{{ url(App::getLocale().'/home') }}">Home</a>
  When I work with databases I usually use this github package to work with translations. Lastly I'd like to show you how to create a language selection button and change the lang of the website without going back to the home page. This has nothing to do with Laravel or PHP but whatever :) The buttons:
<a class="lang-select" lang="en" href="#">En</a>
<a class="lang-select" lang="fr" href="#">Fr</a>
And the javascript:
$('.lang-select').click(function(e){
     e.preventDefault();

     var lang    = $(this).attr('lang');
     var getUrl  = location.pathname;
     var newUrl  = getUrl.replace(getUrl.split("/")[1], lang);
     window.location = newUrl;
});
 

2. Controllers / Middleware

1. Return view with data

My personal favorite way:
return view('view_name', compact('data_1','data_2'));
 

3. Eloquent ORM

1. Many to many relationship process and queries

I love eloquent but sometimes it's a bit hard to remember everything. Especially when it comes to many to many relationships ! Without going to much into details. Let's take a blog website with articles. We will probably have articles and those will have various categories. Our tables:
  • articles
  • categories
  • article_category (pivot table Laravel wants alphabetical order and singular words)
Article model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
    ];


    public function category()
    {
      return $this->belongsToMany('App\Category');
    }
}
Categories model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
    ];

    public function articles()
    {
      return $this->belongsToMany('App\Article');
    }
}
  And now let's say I want to get all the articles with a specific category:
$articles= Article::whereHas('category', function($query) {
            $query->where('category_id', $the_category_id_I_want);
           })->get();
 

4. Blade Template

1. Forms

Note that the following method to create form uses the laravelcollective html package ! Basic form example:
{!! Form::open(['url' => App::getLocale().'/your_url','files' => true]) !!}
    <div class="panel-body">
       <div class="form-group">
          {!! Form::label('name', 'Name', ['class' => 'control-label']) !!}
          {!! Form::text('name', null, ['class' => 'form-control','autocomplete' => 'off']) !!}
       </div>
       <div class="form-group">
          {!! Form::label('image', 'Image', ['class' => 'control-label']) !!}
          {!! Form::file('image') !!}
       </div>
       <div class="form-group">
         {!! Form::label('list', 'List', ['class' => 'control-label']) !!}<br>
         {{ Form::select('list_id', $my_list , null, ['class' => 'group-select','placeholder' => 'Select a option']) }}
       </div>
       <div class="form-group">
         {!! Form::label('description', 'Description', ['class' => 'control-label']) !!}
         {!! Form::textarea('description', null, ['rows' => '5','class' => 'form-control']) !!}
       </div>
       {!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
     </div>
{!! Form::close() !!}
This form has a simple text input , a file upload button, a select list and a textarea. Note 1:  the to allow file upload we add at the beginning of the form:
'files' => true
Note 2: this is how we query data with eloquent to display the data in a select box:
$my_list  = MyModel::lists('field_name','id');