Skip to content

Instantly share code, notes, and snippets.

@mikedfunk
Last active May 18, 2019 19:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mikedfunk/7306887 to your computer and use it in GitHub Desktop.
Save mikedfunk/7306887 to your computer and use it in GitHub Desktop.
Laravel Snippets

Laravel Snippets

Join a table to itself

e.g. a category that can have a parent_id which is another category

public function parent()
{
    return Category::where('id', '=', $this->category_id)->first();
}

Set a checkbox default in the controller

$input = Input::all();
$input['my_checkbox' = Input::get('my_checkbox', 0);

and in the view:

<!-- parameters are: name, value, whether it's checked -->
{{ Input::checkbox('my_checkbox', '1', $item->is_enabled) }}

Input::replace() no longer works

instead pass the input params to call in the third parameter like so:

$this->call('GET', 'my/url/here', $params);

Dynamic drop-down

Controller code:

$imprints_list = Imprint::get(array('id', 'title'));
$imprints[''] = 'Select';
foreach ($imprints_list as $imprint) {
    $imprints[$imprint->id] = $imprint->title;
}
// Bind the array var to the view
return View::make('products.edit')
    ->with('imprint_array', $imprints)

View (Blade) code...

{{ Form::label('imprint_id', 'Imprint:') }}
{{ Form::select('imprint_id', $imprint_array, $item->imprint_id) }}

404 if empty find result

with no extra lines of code!

// will do App::abort(404) if no model found
$my_model = MyModel::findOrFail($id);

doing stuff based on environment

if(App::environment() !== 'local')
{
    //
}

belongs to one with foreign key on first table

public function MyBelongsToOneTable()
{
    return $this->belongsTo('namespaced\MyEloquentModel');
}

mock a collection so you can return it's contents and mock a method call on it

// in the test file
$mock_all = Mockery::mock('\Illuminate\Database\Eloquent\Collection');
$mock_all[0] = Mockery::mock('Einstein\MyElement\MyElementModelInterface');
$mock_all[0]->id = 1;
$mock_all[0]->title = 'whatever';
$mock_all[1] = Mockery::mock('Einstein\MyElement\MyElementModelInterface');
$mock_all[1]->id = 2;
$mock_all[1]->title = 'whatever';

MyElement::shouldReceive('all')
    ->once
    ->andReturn($mock_all);

// now you can add methods chained to all()
$mock_all::shouldReceive('lists')
    ->once()
    ->andReturn($something);

@if statement example

@if($item->is_enabled)
<a href="{{ URL::route('items.show', $item->id) }}">
  <input type="checkbox" class="iButton-icons" checked="checked" />
</a>
@else
<a href="{{ URL::route('items.show', $item->id) }}">
  <input type="checkbox" class="iButton-icons" />
</a>
@endif

form input with class

{{ Form::text('title', null, array('class' => 'whatever')) }}

populate a select list from a model

// in the controller
$my_select_items = MyModel::all()->lists('title', 'id');
// then pass it to the view

// then in the view
{{ Form::select('select_name', $my_select_items) }}

multi select (chzn select)

  <div class="control-group">
    {{ Form::label('data[package][filtered_items]', 'Item Blacklist:', ['class' => 'control-label']) }}
    <div class="controls">
      <select multiple="multiple" name="data[package][filtered_items]" class="chzn-select">
        @foreach($items as $item)
        {{-- if package template is set, select this option *if* it's currently blacklisted for this package template --}}
        <option value="{{ $item->id }}" {{ isset($package) ? ($package->filteredItems->contains($item->id) ? 'selected="selected"' : '') : '' }} >
        {{ $item->title }}
        </option>
        @endforeach
      </select>
    </div><!--controls-->
  </div><!--control-group-->

#Laravel Accessors and Mutators

/**
 * sets the EffectiveDate into Y-m-d format
 * 
 * @param datetime
 */
public function setEffectiveDateAttribute($effective_date)
{
   if ($effective_date) {
       $this->attributes['effective_date'] = date('Y-m-d', (strtotime($effective_date)));
   } else {
       $this->attributes['effective_date'] = null;
   }
}

/**
 * returns the EffectiveDate into m/d/Y format
 * 
 * @param datetime
 */
public function getEffectiveDateAttribute()
{
   $tmpdate = $this->attributes['effective_date'];
   if ($tmpdate == "0000-00-00" || $tmpdate == "") {
       return "";
   } else {
       return date('m/d/Y', strtotime($tmpdate));
   }
}

belongsTo(): many-to-one or one-to-one

in the Dog model

class Dog extends Eloquent()
{
    public function owner()
    {
        return $this->belongsTo('OwnerNamespace\OwnerEloquentModel');
    }
}

the foreign key field owner_id is defined in the dogs_table table.

owners_table
id dog_id (foreign key) title, etc.
dogs_table
id title, etc.

belongsToMany(): many-to-many

in the Employee model

class Employee extends Eloquent
{
    public function employer()
    {
        // tracking happens in the pivot table
        return $this->belongsToMany('EmployerNamespace\EmployerEloquentModel');
    }
}

in the Employer model

class Employer extends Eloquent
{
    public function Employee()
    {
        // tracking happens in the pivot table
        return $this->belongsToMany('EmployeeNamespace\EmployeeEloquentModel');
        
        // You may override the conventional pivot *table_name* and foreign keys as follows
        return $this->belongsToMany(
            'EmployerNamespace\EmployerEloquentModel', 
            'employer_table_employee_table', 
            'employer_name', 
            'employee_name'
        );
    }
}

means that the foreign key fields employer_id and employee_id are defined in the employers_table_employees_table pivot table.

employees_table
id title, etc.
employers_table_employees_table (pivot table)
id employee_id (foreign key) employer_id (foreign key)
employers_table
id title, etc.

hasMany() or hasOne(): one-to-many or one-to-one

in the Owner model

class Owner extends Eloquent
{
    public function dog()
    {
        return $this->hasOne('DogNamespace\DogTableEloquentModel');
        // or
        return $this->hasMany('DogNamespace\DogTableEloquentModel');
        // pass a second parameter if the foreign key is not an ID
        reutrn $this->hasMany('DogNamespace\DogTableEloquentModel', 'owner_name');
    }
}

the foreign key field owner_id is defined in the dogs_table table.

What's the difference? hasOne() returns an individual model, hasMany() returns a collection.

owners_table
id title, etc.
dogs_table
id owner_id (foreign key) title, etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment