Laravel Tips and Tricks

-------------------------------------------
Missing routes.php File in New Laravel Project
-------------------------------------------
The lastest version of Laravel doesn't have a routes.php file.

This 'routes.php' file was located in \app\Http in the older versions.

In the newer version, Laravel 5.3, we have a folder named 'routes', where we can find the following files:

api.php
console.php
web.php
For this new version, the routes for your controllers, you can put inside web.php file

See the documentation about routing here

https://laravel.com/docs/5.3/routing#basic-routing

The video lesson you are watching may be outdated.

-------------------------------------------
Could not open input file: artisan
-------------------------------------------
You need to first create Laravel project and if you already have one you need to go to this project dir using cd command in terminal for example cd myproject.

Now you will be able to run any artisan commands, for example running php artisan will display you list of available commands.

-------------------------------------------
(2/2) ErrorException
Route [student:create] not defined. (View: /home/vagrant/Code/pds/resources/views/student/index.blade.php)

{!! html_entity_decode(Html::link(route('employees:create'),trans('employee.add'))) !!}

changed instead of employees:create changed to employees.create
-------------------------------------------
(1/1) ReflectionException
Class App\Http\Request\StudentRequest does not exist

include this library to the top of the StudentRequest class

use App\Http\Requests\Request;

-------------------------------------------
massassignmentexception _token
-------------------------------
You need to make sure that csrf_token() has to be included in the student._form.blade.php in Laravel 5.4

{!! csrf_token() !!}

-------------------------------------------
[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "middleware" is not defined.
-------------------------------------------
vagrant@homestead:~/sample$ php artisan make:middleware MustBeAdmin
Middleware created successfully.

1. Then menu http->middleware there you can see the MustBeAdmin.php class generated successfully.
2. After that you need to register with in kernal.php here the application's route middleware can be registed.
3. example as a 'admin' => \App\Http\Middleware\MustBeAdmin::class.
--------------------------
(1/1) TokenMismatchException
---------------------------



---------------------------
(1/1) FatalThrowableError
Class 'App\Http\Controllers\Session' not found
---------------------------
Main this is this we need to use the Session in this particular class

Example:
use Session;
-----------------
BootBox Alert
----------------
<a href="{{ route('main.usertypes.destroy', array($usertype->id)) }}" data-method="delete" data-modal-text="{!!trans('main.deletemessage') !!}
{!!strtolower(trans('main.usertype.stitle')) !!}?" data-csrf="{!! csrf_token() !!}">
        <i class="glyphicon glyphicon-trash"></i> {!!trans('main.delete') !!}
</a>

--------------------------------------------------------
How to add extra column in existing table in laravel 5.4
--------------------------------------------------------
Step :1
--------
Need to run the command for altering the table

php artisan make:migration alter_user_table --table=student

step :2
-------
Here need to add the migration script in the file called Illuminate\Database\Migrations\Migration\filename.php.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterToStudentTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('student', function (Blueprint $table) {
            $table->string('email')->unique()->change();
            $table->unsignedInteger('country_id');
            $table->string('gender', 10);
            $table->string('lauguages', 20);         
            $table->string('profile_picture', 200)->nullable()->default(NULL);
            $table->string('password');
            $table->date('date_of_birth');
            $table->foreign('country_id')->references('id')->on('country')->onDelete('cascade')->onUpdate('cascade');
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('student', function (Blueprint $table) {
            Shema::dropIfExists('student');
        });
    }
}
Step :3
--------
After adding the migration script need to execute the

php artisan migrate command
--------------------------------------------------
Modifying Columns
------------------
#Prerequisites
--------------

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:

composer require doctrine/dbal
----------------------------------------------------
[Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
--------------------------------------------------------


----------------------
Why do I have to run “composer dump-autoload” command to make migration work in laravel
----------------------
My Issue:
I have deleted manually in the databases student table. Any how i need to use the sample migration script. In that case the databases->migrations the name will be already exist.
so i will not be able to use the -

composer dumpautoload
----------------------------------------------
How to pass value to Password field in Laravel

Form::input('password', 'name', 'value')
------------------------------------
Laravel Countries

Total Downloads Latest Stable Version Latest Unstable Version

Laravel Countries is a bundle for Laravel, providing Almost ISO 3166_2, 3166_3, currency, Capital and more for all countries.

Please note that version 1.4 is Laravel 5 only, older versions of Laravel should use version 1.3.4 instead

Installation

Add webpatser/laravel-countries to composer.json.

"webpatser/laravel-countries": "dev-master"
Run composer update to pull down the latest version of Country List.

Edit app/config/app.php and add the provider and filter

'providers' => [
    'Webpatser\Countries\CountriesServiceProvider',
]
Now add the alias.

'aliases' => [
    'Countries' => 'Webpatser\Countries\CountriesFacade',
]
Model

You can start by publishing the configuration. This is an optional step, it contains the table name and does not need to be altered. If the default name countries suits you, leave it. Otherwise run the following command

$ php artisan vendor:publish
Next generate the migration file:

$ php artisan countries:migration

It will generate the <timestamp>_setup_countries_table.php migration and the CountriesSeeder.php seeder. To make sure the data is seeded insert the following code in the seeds/DatabaseSeeder.php

//Seed the countries
$this->call('CountriesSeeder');
$this->command->info('Seeded the countries!');
You may now run it with the artisan migrate command:

$ php artisan migrate --seed
After running this command the filled countries table will be available
---------------------------
https://laravel.com/docs/5.4/pagination

------------------------
How do I modify a MySQL column to allow NULL?

My solution:

ALTER TABLE table_name CHANGE column_name column_name type DEFAULT NULL
For example:

ALTER TABLE SCHEDULE CHANGE date date DATETIME DEFAULT NULL;
---------------------
3/3) QueryException
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value (SQL: insert into `users` (`updated_at`, `created_at`) values (2017-08-05 10:43:54, 2017-08-05 10:43:54))



----------
Adding minutes to date time in PHP

---------
<?php
$date = strtotime('Y-m-d H:i:s'.'+ 24 minute');
//$newtimestamp = strtotime($date.'+ 16 minute');
$SetDueDate = date('Y-m-d H:i:s', $date);
var_dump($SetDueDate);

https://stackoverflow.com/questions/8169139/adding-minutes-to-date-time-in-php
-------------
ErrorException in helpers.php line 582: The Mix manifest does not exist.
--------------


Unable to locate Mix file: /css/app.css. Please check your webpack.mix.js output paths and try again
---------------
//echo date('Y-m-d H:i:s', $newtimestamp);

?>

email works
------------
 /* Mail::send('emails.mailEvent', $data, function ($message){
            $message->from('selvi3jai@gmail.com', 'your app');

            $message->to('jemirisselvis@gmail.com')->subject('your reminder');
         }); */
------------------------
search
------
Model:
public static function getCustomersDetails($conditions = false, $orderby = 'name', $order = 'asc')
    {
  $customer = Customer::orderBy($orderby,$order);
  if (isset($conditions['search']) && $conditions['search'] != '') {
            $search = $conditions['search'];
            $customer->where(function ($query) use ($search) {
$query->orwhere('act_no', 'LIKE', '%' . $search . '%');
$query->orwhere('customer', 'LIKE', '%' . $search . '%');
$query->orwhere('name', 'LIKE', '%' . $search . '%');
$query->orwhere('address1', 'LIKE', '%' . $search . '%');
$query->orwhere('city', 'LIKE', '%' . $search . '%');
$query->orwhere('zip', 'LIKE', '%' . $search . '%');
$query->orwhere('phone', 'LIKE', '%' . $search . '%');
$query->orwhere('email', 'LIKE', '%' . $search . '%');
        });
        }
        if (isset($conditions['customer_status']) && $conditions['customer_status'] != '') {
            $search = $conditions['customer_status'];
            $customer->where(function ($query) use ($search) {
                $query->orwhere('customer.status', '=', $search);
            });
        }
        $customer->with('contact', 'order', 'invoice', 'departmentCustomerAddress');
        $paginate_size = Session::get('paginate_size') ? Session::get('paginate_size') : 10;
  return $customer->paginate($paginate_size);
    }

Cotroller:
if (Input::get('search') ) {
Session::put('search', Input::all());
}

$data['customers'] = Customer::getCustomersDetails(Session::get('search'),$data['sortorder'],$data['sortby']);

View:
----
{!! Form::open(array('route' => 'main.equipment.search')) !!}

<div class="form-group" style="float: left;margin-right: 10px;">
                      {!! Form::text('search', @$search_string, array('id'=>'search_id','class' => 'form-control','placeholder'=>trans('main.search').' '.trans('main.equipment.title') )) !!}
                  </div>
      <button type="submit" class="btn btn-primary">{!!trans('main.search') !!}</button>
      {!! Form::close() !!}
-------------
Swift_RfcComplianceException Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
-------------------
Mail config in mail.php
the sender mail was does not come

---------
Trait
---------
trait can be used with the constructor and it can be used as the multiple in heritence.

(i.e)
Use FileUpload Trait;

in use it the functions like
$this->uploadFiles($params1, $params2);
------------
To create the request
---------------
If you have generated request properly by following command

php artisan make:request ContactsRequest

Then create the custom request
------------------------------------------------
(1/1) HttpException This action is unauthorized.
------------------------------------------------
Need to specify the return true in authorization
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserTokenRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'password' => 'required|string|min:6|confirmed'
        ];
    }
}
----------------------------------------------------------------------------------------
(1/1) FatalThrowableError
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in /home/vagrant/Code/pds/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 294
------------------------------------------------------------------------------------------
remove the auth()

-----------
These credentials do not match our records laravel
----------------

----------------------
302 found response
-----------------
The 302 status code indicates that the resource you are requesting has redirected to another resource. If this is behind some authentication, or requiring a session to be active then yes, it would follow that the session timing out is responsible for the ajax resource being called to redirect to possibly a login screen maybe.

------------------------------------------------------
Configuring Homestead to work with MySQL Workbench
-------------------------------------------------------
I was facing the same issue and I tried below steps to fix it. Please let me know if they work for you.

Note the homestead ip address for your vagrant box. It is available in Homestead.yaml file under ~/.homestead directory. This directory location would be different on different OS. But since you have already installed vagrant with homestead you should know its location. For me the ip address was 192.168.10.10.
Open up the Mysql Connection wizard and provide the below settings

hostname  = 192.168.10.10
port = 3306
username = homestead
password = secret

Test Your connection
For me these settings worked. Check if they work for you.
-------------------------------------------------------
how to specify the path to create migration in laravel
-------------------------------------------------------
To create a migration, you may use the migrate:make command on the Artisan CLI:

php artisan make:migration create_users_table

The migration will be placed in your app/database/migrations folder, and will contain a timestamp which allows the framework to determine the order of the migrations.

You may also specify a --path option when creating the migration. The path should be relative to the root directory of your installation:

php artisan make:migration alter_table_project_remove_process_id --path=/database/migrations/tenant
------------------------
#Running Migrations
------------------------
Running All Outstanding Migrations

php artisan migrate
Running All Outstanding Migrations For A Path

php artisan migrate --path=/database/migrations/tenant
-------------------------------------------------------
ternary operator in laravel
-------------------------------------------------------
$var ? $test : 'error fix';
-------------------------------------------------------
Coding Standrad in laravel 5.2
-------------------------------------------------------
Check out PHP PSR 1 and PSR 2 for more info about the coding style. You can also set up sublime text to format your code on button press (or save maybe?) using a package.
DocBlocks are applied automatically if you have a package for it like DocBlockr (just search for it in the package installer in Sublime Text), all you have to do is write /** above the method and press enter (or tab).
For type hinting, you have to do it manually, write the class name or the type of the variable (if you are using PHP 7) and just import the full path at the top of the file like App\Users\User (if the class is in that namespace). You can also automate this with a package called PHP Companion ( I think it was that one) but you have to automate it with shortcuts.
-------------
Installation
-------------
With Package Control
-------------
If you have the Package Control package installed, you can install DocBlockr from inside Sublime Text itself. Open the Command Palette and select "Package Control: Install Package", then search for DocBlockr and you're done!
-------------
Without Package Control
-------------
Go to your Sublime Text 2 Packages directory and clone the repository using the command below:

git clone https://github.com/spadgos/sublime-jsdocs.git DocBlockr
Don't forget to keep updating it, though!
-------------
Without Git
-------------
Download the latest version from the tags page. Unzip to your Sublime Text Packages folder (you can find this by opening ST2 and selecting Preferences -> Browse Packages...). You will need to rename the folder from the default (which will be something like spadgos-sublime-jsdocs-a4bc2a) to DocBlockr. That's it -- you shouldn't even need to restart ST2.
-------------
Docblock completion
-------------
Pressing enter or tab after /** will yield a new line and will close the comment.

/**<<enter>>

-- becomes --

/**
 * |
 */
-------------------------------------------------------
To drop a foreign key table migration script
-------------------------------------------------------
n
-----------------------------------------------------------------------
How to specify the foriegn key value for the string primary key values
-----------------------------------------------------------------------
class CreateProcessTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sample', function (Blueprint $table) {
            $table->string('id', 32)->unique()->index();
            $table->string('name')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

        $this->seed();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('sample');
    }

    /**
     * Seed To seed the sample from the master to tenant
     * @return [array] [sample(s)]
     */
    public function seed()
    {
        try {

            echo get();
           
        } catch (Exception $e) {
            echo $e->getMessage();
        }

    }

}
-----------------------------------------------------------------------------
Cannot add or update a child row a foreign key constraint fails in laravel
-----------------------------------------------------------------------------

-------------------------------------------------------
jQuery BlockUI Plugin
-------------------------------------------------------
$(document).ready(function() {
    $('#demo5').click(function() {
        $.blockUI({
            message: $('#displayBox'),
            css: {
                top:  ($(window).height() - 400) /2 + 'px',
                left: ($(window).width() - 400) /2 + 'px',
                width: '400px'
            }
        });

        setTimeout($.unblockUI, 2000);
    });
});
   
-------------------------------------------------------
laravel : php artisan not working
------------------------------------------------------
Normally when this issue arises it's due to an error in your code. Check for these coporates

Could be a typo in your .env file
Could be a syntax error in your .env
Entering in wrong configuration(syntax error) in your config folder
------------------------------------------------------------
Laravel:Unknown column 'updated_at'
------------------------------------------------------------
In the model, write the below code;

public $timestamps = false;
------------------------------------------------------------
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'project_features' (SQL: select `project_features`.*, `project_features`.`project_id` as `pivot_project_id`, `project_features`.`report_id` as `pivot_report_id` from `project_features` inner join `project_features` on `project_features`.`id` = `project_features`.`report_id` where `project_features`.`project_id` = 71) (View: /home/vagrant/Code/hms2go/resources/views/tenant/project/edit.blade.php)
-------------------------------------------------------
/**
 * The function to define relationship with pivot table to get the WPS Records.
 *
 * @access public
 * @var array
 */
public function reportfeatures()
{
return $this->belongsToMany('Hms2Go\Models\ReportFeaturesModel', 'project_features', 'project_id', 'report_id');
}
------------------------------------------------
(1/1) MethodNotAllowedHttpException
----------------------------------------------
1. Check in the chrome debug mode
(i.e):
Request URL:http://pds.hms2go.dev/project/eyJpdiI6IktrS3laeXhFcjZmVTJKc05DT2xVWUE9PSIsInZhbHVlIjoiZWFvOFFTM0FYQk1PMStaTjdTNjZ5dz09IiwibWFjIjoiM2ZjYzgyMGNmYjdlOTM2MmE0ZWUzOGEyZWVmODhlNTM1YjFhYmI5OGI3NDJkMjBhZDIyY2FhYjM5N2JlYWZkNiJ9
Request Method:POST
Status Code:405 Method Not Allowed

Answer: Route::post('project/{id}', ['as' => 'tenant.project.update', 'uses' => 'ProjectController@update']);

----------------------------------------------
Check Box sample
-----------------------------------------------
 @if(count(@$report_features) > 0) 
  @foreach(@$report_features as $report_key => $report_value)                       
<div cclass="mt-checkbox-list">
<label class="mt-checkbox mt-checkbox-outline">{{ $report_value }}                                                                   
{{ Form::checkbox('report_features[]', $report_key, in_array(@$report_key, @$selected_report_features), ['id'=> $report_key]) }}
   <span></span>
</label>
</div>
@endforeach
@endif
-----------------------------------------------
(3/3) QueryException
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
-----------------------------------------------
 $table->foreign('project_id')->references('id')->on('project')->onDelete('restrict')->onUpdate('cascade');

Answer:
I'm assuming you have a many to many relationship with a pivot table in the middle.

Make sure you add onDelete('cascade') to your foreign key between the pivot table and the categories table

$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
The issue is that you are deleting a row that another table (pivot table) is referencing through a foreign key.

example: $table->foreign('project_id')->references('id')->on('project')->onDelete('cascade')->onUpdate('cascade');
-----------------------------------------------
(1/1) DecryptException
The payload is invalid.
-----------------------------------------------
When the form action and the routes are worng this type of error occurs. This need to check out and need to sorted out
  {!! Form::open([
'method' => 'DELETE',
'role' => 'form' ,
'class' => 'form-horizontal form-validate-jquery',
'id' => 'deleteexpertise',
'url' => route('expertise.index')
])
!!}
{!! Form::close() !!}
-----------------------------------------------
To Load the views active inactive status using icons
-----------------------------------------------
languages:
    'active'           => '<span class="glyphicon glyphicon-ok btn btn-success">&nbsp;Active</span>',
views:
<td>{!!  (@$stud->status==1) ? trans('student.active') : trans('student.inactive') !!}</td>
-----------------------------------------------------------------
laravel export to excel
-----------------------------------------------------------------
To install Laravel Excel run the following command from your Laravel application’s root directory:

$ composer require maatwebsite/excel
Once installed, open config/app.php and add the following line to the bottom of the providers array:

'providers' => [
    ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],
Finally, add the Excel facade to the bottom of the aliases array (also in the config/app.php file):

'aliases' => [
    ...
    'Excel'     => Maatwebsite\Excel\Facades\Excel::class,
],
Save these changes and you’re ready to begin exporting data to an Excel spreadsheet! Let’s work through a simple example. Like many developers lacking design acumen I tend to use the fantastic Bootstrap framework for my administrative consoles, and so the below example will create a stylized hyperlink titled “Export to Excel” and pointing to the URL represented by the route alias admin.payments.excel:

{!! link_to_route('admin.payments.excel',
      'Export to Excel', null,
      ['class' => 'btn btn-info'])
!!}
When rendered to the browser, the button will look like this:



In case you’re wondering, the route alias is defined in the routes.php file, and will look something like this:

Route::get('/payments/excel',
[
  'as' => 'admin.invoices.excel',
  'uses' => 'PaymentsController@excel'
]);
So in this example the Payments controller’s excel() action should contain the logic used to generate and return the Excel file. A commented example follows:
/**
* Download the data to the excel sheet
* @return [file] [Returns the data]
*/
public function excel() {

$ChemicalLists = ChemicalListModel::all();

// Initialize the array which will be passed into the Excel
// generator.
$chemicalListarray = [];

// Define the Excel spreadsheet headers
$chemicalListarray[] = ['id', 'name','description','provider', 'repository','responsible', 'last_revised', 'risk_analysis', 'created_at', 'updated_at'];

// Convert each member of the returned collection into an array,
// and append it to the payments array.
foreach ($ChemicalLists as $list) {
$chemicalListarray[] = $list->toArray();
}

// Generate and return the spreadsheet
Excel::create('chemical_list', function($excel) use ($chemicalListarray) {

// Set the spreadsheet title, creator, and description
$excel->setTitle('Chemical List');
$excel->setCreator('Hms2Go')->setCompany('Hms2Go');
$excel->setDescription('Chemical List file');

// Build the spreadsheet, passing in the payments array
$excel->sheet('sheet1', function($sheet) use ($chemicalListarray) {
$sheet->fromArray($chemicalListarray, null, 'A1', false, false);
});

})->download('xlsx');
}
Once these changes are in place, upon pressing the Export to Excel button the user will be prompted to download the newly generated spreadsheet!

Refer :: http://www.easylaravelbook.com/blog/2016/04/19/exporting-laravel-data-to-an-excel-spreadsheet/
Refer :: http://www.maatwebsite.nl/laravel-excel/docs/export
------------------------------------------------------------------------------
Get table column names as array from Eloquent model or eloquent get column list
------------------------------------------------------------------------------
Need to get the table column names as array from Eloquent model and return to the controller with the data.
Model:
/**
     * The function to define relationship with documents table.
     *
     * @access public
     * @var array
     */
    public function getTableColumns()
    {
        list($columns, $values) = array_divide((new static)->first()->toArray());
        return $columns;
    }

i.e:
echo trim($this->table);
        $connet=  \DB::connection()->getPdo();
        $table = \Schema::getColumnListing('project_process');
        $table = \DB::getSchemaBuilder()->getColumnListing($this->table);
        $table = $connet->getSchemaBuilder()->getColumnListing("document");
        $table = $this->getConnection()->getSchemaBuilder()->getColumnListing($this->table);

Controllers:
$model = ChemicalListModel::find(1);
    $data['column_headers'] = $model->getTableColumns();

-----------------------------------------------------------------
laravel blade uppercase and remove underscore
-----------------------------------------------------------------
To remove the underscore and capitalize the each first word to be an uppercase. Just try this way to gain. I sure it works in laravel 5
Ex:
{{ str_replace('_', ' ', ucwords($chemicallists_value)) }}
-----------------------------------------------------------------
How to handle Undefined Offset in laravel?
-----------------------------------------------------------------
The problem is that $blogs is actually defined and its value is [] (i.e. empty array) so it means that isset($blogs) statement will evaluate to true. Same thing is valid for collections. If a collection is empty (i.e. has no elements but it's defined) isset($blogs) will still evaluate to true but accessing $blogs[0] will cause an Undefined offset: 0 error.

You could try the following solutions:

try the following:

{{ isset($blogs[0]) ? $blogs[0]->title : '' }}
If your using a foreach to get every $blog->title use

@foreach ($blogs as $blog)
  {{ $blog->title }}
@endforeach

-----------------------------------------------------------------
How to send relationship data to view? One to many relationships!
-----------------------------------------------------------------
Database Eloquent Views
Hello, friends!

I need to make drop down list with categories! Somehow, something is not working :(

Model Categories

<?php
class Categorie extends Eloquent{

protected $table = 'categories';

public function product() {

return $this->hasMany('Product', 'categorie_id');
}

}
Model Product

<?php
class Product extends Eloquent{

protected $table = 'products';

public function categorie() {

return $this->belongsTo('Categorie');
}

}
Controller

<?php

class HomeController extends BaseController {

public function index() {
$categories = Categorie::with('product')->get();
return View::make('home', array(
'categories' => $categories
));
}

}
Products View

<select data-placeholder="Select product" style="width:350px;" class="chosen-select" tabindex="5">
            <option value=""></option>
        @foreach ($categories as $categorie)
            {{'<optgroup value="'.$categorie->id.'" label="'.$categorie->name.'">' }}
            {{'<option>'.$categorie->product->name.'</option>'}}
             </optgroup>
        @endforeach
</select>
The thing, is, I get error

ErrorException
Undefined property: Illuminate\Database\Eloquent\Collection::$name (View:
----------------------------------------------------
PHPExcel auto size column width
----------------------------------------------------
If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:

// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));

    $sheet = $objPHPExcel->getActiveSheet();
    $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    /** @var PHPExcel_Cell $cell */
    foreach ($cellIterator as $cell) {
        $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
    }
}
----------------------------------------------------
Set Font Color, Font Face and Font Size in PHPExcel
----------------------------------------------------
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
----------------------------------------------------
Multiple select using jQuery
-------------------------------------------------
Multiple select for while exporting the values from the list of records.
js:
----
var handleMultipleUpdate = function () {

handleCheckboxChecked = function() {
            $( "body" ).on( "click", ".multirow", function() {
                if($(this).is(":checked")) {
                    $('.multirow_ids').prop('checked', true);
                } else {
                    $('.multirow_ids').prop('checked', false);
                }
            });
        }

return {

        //main function to initiate the module
        init: function () {
        handleCheckboxChecked();
        }

    };

}();

jQuery(document).ready(function() {
    handleMultipleUpdate.init();
});

views:
------
{!! Form::checkbox('ids[]', @$expertise->id, false, [ 'class' => 'expertise_multirow_ids']) !!}
-------------------------------------------------------------
Laravel - Switch Case
-------------------------------------------------------------
I'm currently working on a project on which I have users, roles and their profiles.

User model has only email and password fields and roles model has name and description fields. They have their belongsToMany relationship on a pivot table.

I have 3 different profiles for each role on separate model classes which are tied to user model with hasOne relationship. I'm trying to assign profile models to users based on their role as each role has different purposes and different fields.

Example:
switch($roleName) {
        case 'callcenter':
            $this->profile = $this->adminProfile();
            break;
        case 'manager':
            $this->profile = $this->adminProfile();
            break;
        case 'admin':
            $this->profile = $this->adminProfile();
            break;
        case 'student':
            $this->profile = $this->studentProfile();
            break;
        case 'staff':
            $this->profile = $this->staffProfile();
            break;
    }
-------------------------------------------------------------
Call to a member function except() on array
-------------------------------------------------------------
-------------------------------------------------------------
 $(".project_users").siblings('div .fs-dropdown').find('.fs-option').removeClass('disabled');
--------------------------------------
Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist
--------------------------------------------
You need to put SongsTableSeeder into file SongsTableSeeder.php in the same directory where you have your DatabaseSeeder.php file.

And you need to run in your console:

composer dump-autoload
to generate new class map and then run:

php artisan db:seed
I've just tested it. It is working without a problem in Laravel 5
---------------------
Call to a member function make() on null
--------------------------
Steps:

Update composer composer self-update
Delete composer cache located in AppData\Local\Composer
Delete composer global vendor folder: AppData\Roaming\Composer\vendor
Close all of your terminals, shells, command line programs
Start shell as administrator and run composer global update
Maybe the update composer and run shell as administrator parts were crucial. I really don't know why this worked now and before it did not.
---------------
CodeFormatter - sublime
-------------
git clone https://github.com/akalongman/sublimetext-codeformatter.git CodeFormatter
link : https://github.com/akalongman/sublimetext-codeformatter