onsa
12/19/2016 - 11:35 AM

Sample usage of Laravel Controller

Sample usage of Laravel Controller

<?php

class UserController extends \BaseController
{

// CREATE
  $user = new User;
  $user->name = 'John';
  $user->save();

// Restore soft deleted entry.
  $user->restore();

// Create a new user, save it in the database and return it.
  $user = User::create(array('name' => 'John'));
// Retrieve the user by the attributes, or create it if it doesn't exist.
  $user = User::firstOrCreate(array('name' => 'John'));
// Retrieve the user by the attributes, or instantiate a new instance.
  $user = User::firstOrNew(array('name' => 'John'));

// READ
// Find user with id = 1.
  $user  = User::find(1);
// Throw an error if user #1 is not found.
    ::findOrFail(1);
// Specify which database connection to be used.
    ::on('connection-name')->find(1);
// List all users.
  $users = User::all();
// Limit results to entries with more than 100 votes.
    ::where('votes', '>', 100)->firstOrFail();
// Limit results to a specific number of entries.
    ::where('votes', '>', 100)->orderBy('created_at')->take(10)->get();
// Force soft deleted users to be returned.
    ::withTrashed()->where('account_id', 1)->get();
// Return soft deleted users.
    ::onlyTrashed()->where('account_id', 1)->get();
// Use predefined scopePopular function.
    ::popular();

// Check if the returned collection contains an entry with id 2.
  $users->contains(2);

// Return a boolean if the user is soft deleted.
  $user->trashed();

// filtering by related models
// Return only users with notes.
  $users = User::has('notes')->get();
// Return only users with notes whose content contains the string 'customer'.
  $users = User::has('notes', '>=', 3)->get();
    ::whereHas('notes', function($q)
      {
        $q->where('content', 'like', 'customer%');
      })->get();
// Return only users with notes whose current version is higher or equal to 15.
    ::orWhereHas('notes', function($q)
      {
        $q->where('current_version_id', '>=', 15);
      })->get();

// reading with related models
// Eager load users with their team (stored in a different table) - avoiding the n + 1 query problem.
  $users = User::with('team')->get();
// Eager load users with their team and the team contacts (stored in a third table).
    ::with('team.contact')->get();
// Eager load users with only specific posts.
    ::with(array('posts' => function($query)
      {
        $query->where('title', 'like', '%first%');
      }))->get();


// Load related models of an existing loaded model.
  $users->load('author', 'publisher');

// Read a column from a pivot table.
  foreach ($user->roles as $role)
    {
      echo $role->pivot->created_at;
    }

// UPDATE
  $user = User::find(1);
  $user->email = 'john@foo.com';
  $user->save();

// Update a model together with its relationships.
  $user->push();
// Update several models just retrieved.
  $affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));

// inserting related models
// Attach new note to an existing user.
  $note = new Note(array('content' => 'A new note.'));
  $user = User::find(1);
// if only one note is to be saved
  $note = $user->notes()->save($note);
// if an array of notes is to be saved
  $user->notes()->saveMany($comments);

// Associate an existing account with an existing user. (One to One)
  $account = Account::find(10);
  $user->account()->associate($account);
  $user->save();

// Attach an existing role with an existing user. (One to Many)
  $user = User::find(1);
// Passed parameter can be id or array of ids.
  $user->roles()->attach(1);
// Second parameter is an optional column-value pair to be saved on the pivot table.
    ->attach(1, array('expires' => $expires));
    ->attach([1 => ['expires' => $expires[1]], 2, 3]);
    ->detach(1);
// Delete all entries for the model on the pivot table (related model remains untouched)
    ->detach();
// Synchronise two models. (= attach all passed parameters, detach all others)
    ->sync(array(1, 2, 3));
    ->sync(array(1 => array('expires' => true)));

// Update pivot table attribute.
  $user->roles()->updateExistingPivot($roleId, $attributes);

// DELETE
  $user = User::find(1);
  $user->delete();

// Delete one or more users by passing id(s).
  User::destroy(1);
    (array(1, 2, 3));
    (1, 2, 3);

// Delete users just retrieved.
  $affectedRows = User::where('votes', '>', 100)->delete();
// Truely delete user despite the softdelete trait.
  $user->forceDelete();

// COLLECTIONS
// Transform collection into array.
  $roles = User::find(1)->roles->toArray();
// Transform collection into json.
    ->toJson();
  $roles = (string) User::find(1)->roles;

// Collections can be iterated over.
  $user->roles->each(function($role) {});
// Collections can be filtered.
  $users = $users->filter(function($user)
    {
      return $user->isAdmin();
    });

// Collections can be sorted by a column.
  $roles = $roles->sortBy('created_at');
  $roles = $roles->sortBy(function($role)
  {
    return $role->created_at;
  });
}