Skip to content

this is a repository when you want to learn laravel from beginner to advanced

Notifications You must be signed in to change notification settings

dakasakti/laravel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel

this is a repository when you want to learn laravel from beginner to advanced

Requirements

Installation

  • Composer

    composer create-project laravel/laravel example-app
    
  • Laravel Installer

    composer global require laravel/installer
    
    laravel new example-app
    

Extension VS Code (Opsional)

Configuration or Environment

Check in Here

// get data
config("app.name", "Laravel")

// use Illuminate\Support\Env;
env('APP_NAME', "defaultValue"); => Env::get('APP_NAME', "defaultValue");

// use cache to load data (production)
php artisan config:cache

// remove cache
php artisan config:clear

Service Provider (Dependency Injection)

Check in Here

php artisan make:provider NameServiceProvider

public function register()
{
    $this->app->singleton(Foo::class, function ($app) {
        return new Foo();
    });

    $this->app->singleton(Bar::class, function ($app) {
         return new Bar($app->make(Foo::class));
    });
}

// use Illuminate\Contracts\Support\DeferrableProvider;
// use Lazy loading (implements DeferrableProvider)
public function provides(): array
{
    return [HelloService::class, Foo::class, Bar::class];
}

// remove compiled cache services
php artisan clear-compiled

// registration service provider
// add in config->app.php => providers
App\Providers\NameServiceProvider::class,

Facades

Check in Here

use facades if required

// in dependency (container)
$config = $this->app->make('config');
$config->get('example.author');

// in facade
Config::get('example.author');

Laravel Debugbar & IdeHelper

composer require barryvdh/laravel-debugbar --dev
composer require barryvdh/laravel-ide-helper --dev

// add in config->app.php => providers
Barryvdh\Debugbar\ServiceProvider::class,

// use
Debugbar::info("message is info");
Debugbar::error("message is error"); 

// helper
php artisan ide-helper:generate
php artisan ide-helper:models

HTTP Response in Routing

Check in Here

  • Send view

    Route::get('/', function () {
        return view('welcome');
    });
    
  • Send string

    Route::get('/string', function () {
        return "Hello World";
    });
    
  • Send array (JSON)

    Route::get('/array', function () {
        return ["PHP", "Laravel"];
    });
    
  • Send JSON (Object)

    Route::get('/json', function () {
        return response()->json([
            "username" => "dakasakti",
        ]);
    });
    
  • Send function

    Route::get('/function', function () {
        return redirect("/);
    });
    
  • Send Fallback

    Route::fallback(FallbackController::class);
    
// use cache view
php artisan view:cache

// remove cache view
php artisan view:clear

Controllers

Check in Here How to make

  • Terminal
    php artisan make:controller -help
    
  • Extenstion VS Code
    CTRL + Shift + P (Windows) => artisan make controller
    

Controller type

  • Basic (without method)
  • Invoke (one method)
  • Resource (complete)

Passing Data to the Views

  • Compact method

    public function index() {
        $title = "This is title";
    
        return view("index", compact("title"));
    }
    
  • With method

    public function index2() {
        $data = "Data title";
    
        return view("index")->with("data", $data);
    }
    
  • Directly

    public function index3() {
        $description = "Data description";
    
        return view("index", [
            "description" => $description,
        ]);
    }
    

Route Parameters

Check in Here

Route::get("/products/{id}", [ProductController::class, "show"]);

public function show($id) {
    return view("index", [
        "id" => $id,
    ]);
}

Pattern parameter Check in Here

Route::get("/products/{id}", [ProductController::class, "show"])->where("id", "[0-9]+");

Named Routes

Check in Here

Route::get("/products", [ProductController::class, 'index'])->name("products");

<h4>Link : <a href="{{ route("products") }}">Click in Here</a></h4>

Views

Check in Here

  • Layouts

    @yield('content') => opsional
    
    extends('layouts.app')
    @section('content')
        <h1>This is main page</h1>
    @endsection
    
    @stack('scripts') => opsional
    
    extends('layouts.app')
    @push('scripts')
        <script src="app.js"></script>
    @endpush
    
    @include('layouts.header') => required
    
  • Images

    php artisan storage:link
    
    <img src="{{ asset("storage/banner.jpg") }}" alt="image">
    
  • Statement

    @if (5 < 10)
        <img src="{{ asset("storage/banner.jpg") }}" alt="image">
    @endif
    
    public function index() {
        return view("portfolio.index")->with("name", "dakasakti");
    }
    
    // reverse in if
    @unless (empty($name))
        <h2>{{ $name }}</h2>
    @endunless
    
    @empty($name)
        <h2>Name is empty</h2>
    @endempty
    
    @isset($name)
        <h2>Name has been set</h2>
    @endisset
    
    @switch($name)
        @case("dakasakti")
            <h2>Welcome, {{ $name }}</h2>
            @break
        @default
            <h2>Welcome, Admin!</h2>
    @endswitch
    
    <div class="row">
        @for ($i = 1; $i <= 5; $i++)
            <div class="col">Column {{ $i }}</div>
        @endfor
    </div>
    
    public function index() {
        $names = ["david", "michelle", "kaila"];
        return view("portfolio.index", compact("names"))->with("name", "dakasakti");
    }
    
    <ul>
        @foreach ($names as $item)
            <li>{{ $item }}</li>
        @endforeach
    </ul>
    
    <ul>
       @forelse ($names as $item)
            <li>{{ $item }}</li>
       @empty
            <li>There are no names!</li>
       @endforelse
    </ul>
    

Compiling Assets (CSS & JS)

Check in Here

Databases & Migration

php artisan make:controller PostController
php artisan make:model Post -m

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId("user_id");
    $table->string("title");
    $table->string("slug")->unique();
    $table->text("body");
    $table->timestamps();
    $table->timestamp("published_at")->nullable();
});

php artisan migrate

Factory Model

Check in Here

php artisan make:factory PostFactory

// PostFactory
public function definition()
{
    $title = fake()->sentence(2);

    return [
        'title' => rtrim($title, '.'),
        'slug' => Str::slug($title, '-'),
        'body' => fake()->paragraph(),
        'user_id' => rand(1,5),
    ];
}

// Seeder
php artisan make:seeder PostFactory

\App\Models\User::factory(10)->create();
\App\Models\Post::factory(10)->create();

php artisan db:seed

Query Builder

Check in Here

use Illuminate\Support\Facades\DB;

// get all post
$posts = DB::table('posts')->get();

// get by id
$posts = DB::table('posts')->where("id", "=", 8)->get();
$posts = DB::table('posts')->where(["id" => 8])->get();

// insert
$posts = DB::table('posts')->insert([
    "title" => "Ini Post Terbaru",
    "slug" => "ini-post-terbaru",
    "body" => "ini deskripsi yang akan ditampilkan",
    "user_id" => 3,
]);

// update
$posts = DB::table('posts')->where(["id" => 11])->update([
    "body" => "mencoba update"
]);

// delete
$posts = DB::table('posts')->where(["id" => 11])->delete();
$posts = DB::table('posts')->delete(11);

Eloquent Model Conventions

Check in Here

\App\Models\{model_name}.php;

// default plural in model_name file
protected $table = "posts";

// default id
protected $primaryKey = "slug";

// default true
protected $timestamps = false;

// multi database
protected $connection = "sqlite";

// default value
protected $attributes = [
    "is_published" => true
];

// mass assignment
protected $fillable = ["title"];

// reverse mass assignment
protected $guarded = ["id"];

Introduction to Eloquent

Check in Here

use App\Models\Blog;

// get all
$blogs = Blog::all();
$blogs = Blog::get();

// get by id
$blog = Blog::find($id);
$blog = Blog::findOrFail($id);

// insert version_1
$blog = new Blog;
$blog->title = $request->input("title");
$blog->slug = $request->input("slug");
$blog->body = $request->input("body");
$blog->user_id = 1;
$blog->save();

// insert version_2
Blog::create([
    "title" => $request->input("title"),
    "slug" => $request->input("slug"),
    "body" => $request->input("body"),
    "user_id" => 1,
]);

// update
public function update(UpdateBlogRequest $request, Blog $blog)
{
    $blog->update([
        "title" => $request->input("title"),
        "slug" => $request->input("slug"),
        "body" => $request->input("body"),
        "user_id" => 1,
    ]);

    return redirect(route("blog.index"));
}

// delete
public function destroy(Blog $blog)
{
    $blog->delete();
    return redirect(route("blog.index"));
}

Eloquent Serialization

Check in Here

  • toArray
$blogs = Blog::all()->toArray();
  • toJSON
$blogs = Blog::all()->toJson();

Eloquent Relationship

Check in Here

  • Eloquent One to Many
  • Eloquent HasMany & HasOne
  • Eloquent Many to Many

Accessing to Request (Validation)

Check in Here

public function rules()
{
    return [
        "title" => "required",
        "slug" => "required",
        "body" => "required"
    ];
}

<!-- /resources/views/blogs/create.blade.php -->
    
<h1>Create Post</h1>
    
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
    
// errors directive
<!-- Create Post Form -->

<!-- /resources/views/blogs/create.blade.php -->
    
<label for="title">Post Title</label>
    
<input id="title"
    type="text"
    name="title"
    class="@error('title') is-invalid @enderror">
    
@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Image Upload

Check in Here

in form => enctype="multipart/form-data"
Method we can use on $request
// guessExtension() => get extension file
// getMimeType() => get type file
// getSize() => get size file
// getError() => get error file
// isValid() => get valid file

// guessClientExtension() => get extension file from client
// getClientOriginalName() => get original name file from client
// getClientMimeType() => get type file from client

// move()
// store()
// storeAs()
// storePublicly()

Paginate

Check in Here

// controller 
call method => paginate(10)

// view
{{ $posts->links() }}

Basic Artisan Commands

Check in Here

php artisan --version
php artisan help
php artisan list
php artisan down
php artisan up
php artisan optimize
php artisan cache:clear
php artisan auth:clear-resets
php artisan key:generate
php artisan session:table
php artisan view:Clear
php artisan serve

Authentication & Authorization

Check in Here

php artisan ui tailwindcss --auth

Testing

Check in Here

php artisan make:test ContohIntegationTest
php artisan make:test ContohUnitTest --unit

public function test_routing_string()
{
    $response = $this->get('/string');

    $response->assertStatus(200);
    $response->assertSeeText("Hello World");
}

php artisan test

REST API

  • REST -> an architectural style used for communication between a server and client.
  • REST -> uses HTTP
  • REST -> data will be send in either XML or JSON
Disadvantages REST

- REST is not stateful
- you can't push data through REST
- you always need to send some kind of context the server

HTTP Method & Service Responses

CRUD    REQUEST     HTTP VERB   ENDPOINT
Read    GET         GET         /blogs
                                /blogs/{inception}
Create  GET         GET         /blogs/create
Update  UPDATE      PUT/PATCH   /blogs/{inception}
Delete  DELETE      DELETE      /blogs/{inception}
Recomendation => consistency is key
- use plural verb

Check in Here

Status Codes
- 2xx => tells the client a request was successful
- 3xx => tells the client about redirections
- 4xx => tells the client that there has been an error
- 5xx => statuses that deal with the server

JSON API Best Practices

Example

- API Spesification
- attribute writing using snake_case

Laravel Passport

Check in Here

  • Laravel Sanctum => does not support OAuth2

You have to set Accept:application/json header in your API request from client-side and Laravel will automatically return a JSON format error.

Access Tokens

php artisan passport:install

How to Make access token ([POST] => {uri}/oauth/token)
grant_type=password
client_id=2
client_secret=randomString
[email protected]
password=defaultusers
scope=

Building Resources

php artisan make:resource BlogResource

public function toArray($request)
{
    return [
        "id" => $this->id,
        "author" => $this->user->name,
        "title" => $this->title,
        "slug" => $this->slug,
        "image_path" => asset("/storage/images/$this->image_path"),
        "body" => $this->body,
        "created_at" => $this->created_at,
        "updated_at" => $this->updated_at
    ];
}

About

this is a repository when you want to learn laravel from beginner to advanced

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published