Skip to content

Instantly share code, notes, and snippets.

@afandiyusuf
Last active November 22, 2017 06:00
Show Gist options
  • Save afandiyusuf/e0e93b88ae6d50b898f493709acb0fb5 to your computer and use it in GitHub Desktop.
Save afandiyusuf/e0e93b88ae6d50b898f493709acb0fb5 to your computer and use it in GitHub Desktop.
Laravel cheatsheet

First Step

Requirement of laravel

  • PHP >= 5.6.4
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Install laravel by composer

composer create-project --prefer-dist laravel/laravel blog "5.4.*"

Serve developoment server.

php artisan serve

php code for using .env

env("STRING NAME",default value)

Note about storage

The storage/app/public directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at public/storage which points to this directory. You may create the link using the

php artisan storage:link command.

Second Step

Routing

Route::get('user/profile', 'UserController@showProfile')

Group Routing

Route::prefix('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
    Route::get('user/profile', 'UserController@showProfile')
});

Route Parameters

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});
Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Third Step

Middleware

php artisan make:middleware CheckAge
 if ($request->age <= 200) 
{
    return redirect('home');
}

    return $next($request);

Note

Assigning Middleware To Routes If you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:

Route::get('admin/profile', function () {
    //
})->middleware('auth');
Route::get('/', function () {
    //
})->middleware('web');

Route::group(['middleware' => ['web']], function () {
    //
});



Middleware Parameters


Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');

public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

Fourth Step

Migration

php artisan make:migration create_users_table --create=users

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('address');
            $table->timestamps();
        });
        
        
Schema::drop('flights');

Migration documentation

https://laravel.com/docs/5.4/migrations

Foreign key

$table->foreign('user_id')->references('id')->on('users');

Fifth Step

Eloquent

Create model

php artisan make:model User

//add this for custom table
protected $table = 'my_user_table';

Model variable

custom primary key

$primaryKey = "column of primary key";

table without timestamp (created_at, updated_at)

public $timestamps = false;

mass assigment

protected $guarded = ['price'];

Relationship

return $this->hasOne('App\Phone');
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->belongsTo('App\User');
return $this->hasMany('App\Comment');
return $this->belongsToMany('App\Role', 'role_user');
return $this->belongsTo('App\User')->withDefault(function ($user) {
        $user->name = 'Guest Author';
    });
    
//get relationship attribute
$user = App\User::find(1);

$user->posts()->where('active', 1)->get();
//get relationship existence
$posts = App\Post::has('comments')->get();
$posts = Post::has('comments', '>=', 3)->get();
$posts = App\Post::doesntHave('comments')->get();
//save relation method
$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$post->comments()->save($comment);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment