Skip to content

Instantly share code, notes, and snippets.

@mayooresan
Last active January 11, 2017 08:17
Show Gist options
  • Save mayooresan/01747a21d1582029adf1 to your computer and use it in GitHub Desktop.
Save mayooresan/01747a21d1582029adf1 to your computer and use it in GitHub Desktop.
Laravel 5.2 - Jay's notes

Laraval Commands

php artisan - common comands
php artisan tinker - playground

Create a controller :

php artisan make:controller ArticlesController

Create model

-m can be used to create the migration plan too. Else just Article is enough.

create the model & schema:  php artisan make:model Article -m

Create table

for schema :

php artisan make:migration create_notes_table --create=notes

create table in db :

php artisan migrate

create the model :

php artisan make:model Note

Query

to make use of the Query

use DB;

to display the sql query in the tinker

DB::listen(function($query) { var_dump($query->sql); });

query all :

DB::table('cards')->get();

query one row :

DB::table('cards')->where('title','my card')->first();

Insert a row

$note = new App\Note
$note->body = 'some note for the card';
$note->card_id = 1
$note->save();

$article = App\Article::create(['title'=>'another article', 'body'=>'another article body is here']);

Update row

$article::update([‘title'=>'another article', 'body'=>'another article body is here']);

ORM Query methods

Query all :

App\Card::all();

Query first row :

App\Card::first()

Query based on id :

$article = App\Article::find(1)

Query with where clause :

$articles = App\Article::where('title','updated the article')->get();

Delete a note

App\Note::find(1)->delete();

CONFIGS

Incase you get cipher key error : php artisan key:generate

Type of relationships

belongsTo
hasMany

Save an item with relationship. Here the new note will get automatically associated with the card.

$note = new App\Note;
$note->body = "here the tinker body";
$card = App\Card::find(2);
$card->notes()->save($note);

Sample on how to get data belongs to a relationship

$card->notes[0]->user; //get the user belongs to the note
$card->notes; //get all the notes belongs to the card
//ps: make sure Note class denotes the relationship between card & user.
//e.g.
public function card(){
	return $this->belongsTo(Card::class);
}

public function user(){
return $this->belongsTo(User::class);
}

//When we have the card object on hand, we can initiate eagerloading as blow
public function show(Card $card){
    $card->load('notes.user');
    return view('cards.show', compact('card'));
}

Eagerload example

App\Card::with('notes')->get(); //it'll load all notes associated along with a card - it'll return array
App\Card::with('notes')->find(1); //it'll load as above but only return a card object

//eager load both user and notes belongs to the Card
App\Card::with('notes.user')->find(1);

Form validations

//put this in controller
$this->validate($request, [
    'email'=>'email|unique:users|',
    'name'=>'required|max:120',
    'password'=>'required|min:4'
]);

//sample html to display error messages
@if(count($errors)>0)
<div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
        <ul>
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    <div class="col-md-4"></div>
</div>
@endif

// retain the value on form after submit & error handling
value="{{Request::old('email')}} //For an input with name="email"

// Adding bootstrap error class to form
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">

Helper functions

Encrypt the password

bcrypt() 

User Authentication

//Use this class for Auth releated built in functions
use Illuminate\Support\Facades\Auth;

//Normal sigin
if (Auth::attempt(['email'=>$request->email, 'password'=>$request->password])){
    return redirect()->route('dashboard');
}else{
    return back();
}

//Programatically sigin using the user object
Auth::login($user);

//When have multiple roles, we can do blade templating as below to restric content
//based on user role
@if ( Auth::user()->role_id == 1 )
	<a href="/admin">இங்கே சொடுக்குக</a>
@endif

Add this input with each login / signup forms

// form syntax
<input type="hidden" name="_token" value="{{ csrf_token() }}">
// Blade Template Syntax
{{ csrf_field() }}

Seeder

php artisan make:seed RolesTableSeeder // create seeder class

//update the class as below
<?php

use Illuminate\Database\Seeder;
use \App\Role;

class RolesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
 * @return void
     */
    public function run()
    {
        $role_admin = new Role();
        $role_admin->name = 'Admin';
        $role_admin->save();

        $role_guest = new Role();
        $role_guest->name = 'Guest';
        $role_guest->save();
    }
}
	
//run the following command to populate
php artisan db:seed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment