this is a repository when you want to learn laravel from beginner to advanced
- PHP >= 8.0 Check in Here
- Composer Check in Here
- NodeJS Check in Here
- Visual Studio Code Check in Here
-
Composer
composer create-project laravel/laravel example-app
-
Laravel Installer
composer global require laravel/installer laravel new example-app
- Laravel Artisan => Ryan Naddy
- Laravel Blade Snippets => Winnie Lin
- Laravel Blade Spacer => Austen Cameron
- Laravel Extra Intellisense => amir
- Laravel goto view => codingyu
- Laravel Snippets => Winnie Lin
- Getter and Setter Generator => Agustin Martinez Ibarra
- PHP Intelephense => Ben Mewburn
- PHP IntelliSense => Damjan Cvetko
- JavaScript (ES6) code snippets => charalampos karypidis
- Database Client => Weijan Chen
- Community Material Theme => Equinusocio
// 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
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,
use facades if required
// in dependency (container)
$config = $this->app->make('config');
$config->get('example.author');
// in facade
Config::get('example.author');
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
-
Route::get('/', function () { return view('welcome'); });
-
Route::get('/string', function () { return "Hello World"; });
-
Route::get('/array', function () { return ["PHP", "Laravel"]; });
-
Route::get('/json', function () { return response()->json([ "username" => "dakasakti", ]); });
-
Route::get('/function', function () { return redirect("/); });
-
Route::fallback(FallbackController::class);
// use cache view
php artisan view:cache
// remove cache view
php artisan view:clear
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)
-
public function index() { $title = "This is title"; return view("index", compact("title")); }
-
public function index2() { $data = "Data title"; return view("index")->with("data", $data); }
-
public function index3() { $description = "Data description"; return view("index", [ "description" => $description, ]); }
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]+");
Route::get("/products", [ProductController::class, 'index'])->name("products");
<h4>Link : <a href="{{ route("products") }}">Click in Here</a></h4>
-
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
-
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>
- Database Check in Here
- Migration Check in Here
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
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
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);
\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"];
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"));
}
- toArray
$blogs = Blog::all()->toArray();
- toJSON
$blogs = Blog::all()->toJson();
- Eloquent One to Many
- Eloquent HasMany & HasOne
- Eloquent Many to Many
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
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()
// controller
call method => paginate(10)
// view
{{ $posts->links() }}
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
php artisan ui tailwindcss --auth
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 -> 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
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
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
- API Spesification
- attribute writing using snake_case
- 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.
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=
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
];
}