No | Day | Total Topics |
---|---|---|
1 | day1 | 10 |
2 | day2 | 7 |
No | Topics |
---|---|
1 | laravel-introduction |
2 | Laravel setup Laravel Herd |
3 | laravel-installation |
4 | Folder Structure |
5 | routing-basics |
6 | routing-parameters |
7 | Laravel Named Route |
8 | Laravel Blade |
9 | Laravel Blade II |
10 | Laravel Blade III |
-
- Laravel is a free, open-source and one of the
more popular
PHP web Framework
based onMVC
architectural pattern. - created by Taylor Otwell in june 2011
- Laravel Followes MVC Pattern
- Laravel is a free, open-source and one of the
more popular
-
- Create Web Apps
- Create APIs
-
- Model
- Database Related Task
- SQL Queries
- View
- User interface
- HTML,CSS
- Controller
- Business Logic
- Mediator between Model and View
- MVC Principle
- Separation of concerns.
- Code Organization
- Model
-
- Controller (controllers/my_controller.php)
function total_frogs(){ Sthis->load->model("frogs"); Snumber_of_frogs= Sthis->frogs->count_frogs(); $data['froggies']=$number_of_frogs; $this->load->view("frog_view", $data); }
- Model (models/frogs.php)
function count_frogs(){ Sthis->db->where("type","frog"); Sthis->db->from("animals"); & Squery = Sthis->db->get(); return $query->numb_rows(); }
- View (views/frog_view.php)
<html> <body> <h1>You've <?=$name;?></h1> </body> </html>
-
- Organized Code
- Independent Block
- Reduces the complexity of Web Applications
- Easy to maintain
- Easy to modify
- Code reusability
- Improved collaboration *
- Platform independence
-
- Laravel
- Symfony
- Codelgniter
- Yii
- CakePHP
- Zend Framework
-
-
Programming frameworks are sets of pre-written code and libraries that provide a foundation for developing software applications.
-
Pre-written Code & Library
- Tools
- Components
- Modules
-
Examples
- Database Component
- Caching
- Pagination
- Session management
- Form Handling
- Security mechanisms
- User authentication
- APIs
- Payment Gateways
-
Benefits
- Code organization
- Reusability
- Standardization
- Testing & debugging support
- Community and support
-
-
- Open source
- Elegant syntax
- MVC architecture
- Database migration and ORM
- Robust routing system
- Command-line Interface (Composer)
- Powerful template engine (Blade Template)
- Authentication and authorization
- Testing and debugging
- Security (XSS, CSRF, SQL injection)
- Scalability and performance (Redis and Memcached)
- Robust ecosystem and community
- Laravel Documentation
-
- Artisan CLI
- Migration
- Routing
- Middleware
- Views
- Form Validation
- Blade Template
- Authentication
- Controllers
- Handling File Upload
- Model
- APIs Validation
- Database
- CRUD Project
- Eloquent ORM
- News Blog Project
-
composer create-project laravel/laravel example-app
- composer create-project laravel/laravel=10 myProject
-
- PHP IntelliSense (Damjan Cvetko)
- PHP Namespace Resolver (Mehedi Hassan)
- Laravel Extra Intellisense (amir)
- laravel-blade (Christian Howe)
- Laravel Blade Snippets (Winnie Lin)
- Laravel goto view (codingyu)
-
- Model Folder ————————> Database / SQL Queries Handling 1. Files
- Controller Folder —————> Business Logics Files
- View Folder ——————————> HTML Files
- Routing Folder ——————> URL Defining Files
- Assets Folder (Public folder) —————————> Images / Fonts / Music / Videos Files CSS / JavaScript Files
-
Route::get('/', function () { return view('welcome'); });
- php artisan
- php artisan route -h
- php artisan route:list
- php artisan route:list --except-vendor
- php artisan route:list --path=post
-
http://localhost/post/yahoobaba http://localhost/post/news10 http://localhost/post/@news10 Route::get('/post/{id}, function (string $id) { return 'User ' . $id; });
- ‘http://localhost/post/10 whereNumber('id')
- http://localhost/post/nabin whereAlpha('name’)
- http://localhost/post/news10 whereAlphaNumeric('name’)
- http://localhost/post/song whereln('category', ['movie', song’)
- http://localhost/post/@10 where('id', '[@0-9]+')
Route::get('/post/{id}', function (string $id) { return 'User '. Sid; })->whereNumber('id');
- Named Route
Route::get('/hjfbvjhfd', function () { return view('post'); })->name('mypost');
- Routes Group
Route::prefix('page')->group(function () { Route::get('/about', function () { return view('welcome'); })->name('myhome'); Route::get('/gallery', function () { return view('welcome'); })->name('gallery'); Route::get('/post', function () { return view('post'); })->name('post'); });
- Page Note Found 404
Route::fallback(function () { return "<h1>Page Note Found.</h1>"; });
flowchart LR
A(Blade Template)
A--->B(Template Engine Based on PHP)
-
Benefits : Create Dynamic and Reusable Templates
-
Blade provides a clean and convenient way to create views in Laravel
-
Same code with php and blade template
// php <?php echo "Hello"; ?> <?php echo $name; ?> <?php echo "<h1>Hello</h1>" ?> // blade template {{"Hello"}} {{$name}} {{!! "<h1>Hello</h1>" !!}}
-
Blade Prevent: cross-site scripting (XSS) Attacks
<?php //php code ?> @php {--commet--} @endphp
-
Basic syntex of blade
<?php if(condition){ //statement }else{ //statement } ?> //blade @if(condition) //statement @else //statement @endif
-
if in blade
@switch($i) @case(1) //first case @break @default //default case @endswitch
-
switch in blade
@isset($record) //$record is default and is not null @endisset
-
isset in blade
-
@for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor @foreach ($users as $user) <p>This is user {{ $user }</p> @endforeach @while (condition) <p>Loop Statement</p> @endwhile @forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse @continue @break
-
Loops for, foreach, while, forelse
Property Description $loop->index The index of the current loop iteration (starts at 0). $loop->iteration The current loop iteration (starts at 1). $loop->remaining The iterations remaining in the loop. $loop->count The total number of items in the array being iterated. $loop->first Whether this is the first iteration through the loop. $loop->last Whether this is the last iteration through the loop. $loop->even Whether this is an even iteration through the loop. $loop->odd Whether this is an odd iteration through the loop. $loop->depth The nesting level of the current loop. $loop->parent When in a nested loop, the parent's loop variable. @php $names = ['surej', 'rajan', 'himal', 'nabin']; @endphp <ul> @foreach ($names as $name) @if ($loop->even) <li style="color: red">{{ $name }}</li> @elseif ($loop->odd) <li style="color: green">{{ $name }}</li> {{-- @else <li>{{ $name }}</li> --}} @endif @endforeach </ul>
-
Basic example
-
Blade Loop Variable for
@foreach
- Including Subviews/Directives
- @include
- @section
- @extend
- @yield
- Reusable Templates
first.blade.php second.blade.php <h1>First Page</h1> <h1>Second Page</h1> {{ $status }} `Include View` @include(first) @include() @include('first', ['status' => 'Hello'])
- passing props in laravel
{{-- @include --}} {{-- prpos --}} @php $fruits = ['one' => 'Apple', 'two' => 'Mango', 'three' => 'banana', 'four' => 'orange']; $age = 20; @endphp {{-- @include('pages.header', ['names' => $fruits]) --}} {{-- @includeWhen($age > 18 ? true : false, 'pages.header', ['names' => $fruits]) --}} @includeUnless($age > 18 ? true : false, 'pages.header', ['names' => $fruits]) <h1>Home page</h1> @include('pages.footer') @includeIf('pages.contact')
- Template main directives
- @section
- @extend
- @yield
- template inheritance
// master layout
@yield('title', 'web')
// other pages
@extends('layouts.masterlayout');
@section('content')
<h2>Home page</h2>
<p>Lorem ipsum dolor sit amet consectetur</p>
@endsection
@section('title')
Home
@endsection
// master layout
@hasSection('content')
@yield('content')
@else
<h1>No Content Found</h1>
@endif
// other
@section('sidebar')
@parent
<p>This is appended to the sidebar</p>
@endsection
No | Topics |
---|---|
11 | js in balde |
12 | data-passing |
13 | controller |
14 | features-of-laravel-11 |
15 | database-migration |
16 | migration-modifiers |
17 | migration-primary-foreign-key |
-
- How to write js in blade template
@php $user = 'Hello'; $frouts = ['Apple', 'Mango', 'Banana', 'Litchi']; @endphp <script> // let data = @json($frouts); let data = {{ Js::from($frouts) }} data.map((val) => { console.log(val); }) </script>
- Js in Template Inheritance
//define @stack('script') //use @extends('layout') @push('script') <script src="/example.js"></script> @endpush
- style (CSS)
@push('style') <link rel="stylesheet" href="css/bootstrap.css"> @endpush @prepend (‘style’) <style> #wrapper{ background: tan; } </style> @endprepend
- javascript Framework (VueJs)
@verbatim {{user}} @endverbatim
- use Vue.js in laravel
@verbatim <div id="app">{{ message }}</div> @endverbatim @push('scripts') <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <script> const { createApp, ref } = Vue createApp({ setup() { const message = ref('Hello vue!') return { message } } }).mount('#app') </script> @endpush
-
- Dynamic Data Passing
function getUsers() { return [ 1 => ['name' => 'Amitabh', 'phone' => '9123456789', 'city' => 'Goa'], 2 => ['name' => 'Salman', 'phone' => '9123456789', 'city' => 'Delhi'], 3 => ['name' => 'Sunny', 'phone' => "9123456789", 'city' => 'Mumbai'], 4 => ['name' => 'Akshay', 'phone' => '9123456789', 'city' => 'Agra'], ]; } Route::get('/users', function () { $names = getUsers(); return view('users', [ 'users' => $names, 'city' => 'Delhi' ]); }); Route::get('/user/{id}', function ($id) { $users = getUsers(); abort_if(!isset($users[$id]), 404); $user = $users[$id]; return view('user', ['id' => $user]); })->name("view.user");
-
- To work on controller we should follow these three steps
- Create Controller File
- To create Controller:
php artisan make:controller UserController
- Then it will create:
UserController.php
class UserController extends Controller { public function show() { return view('user.profile'); } } // then add it to route use App\Http\Controllers\UserController; Route::get('/user', [UserController::class, 'show']);
- Create Controller class
- Create Route
PageController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PageController extends Controller { public function showHome() { return view("welcome"); } public function showUser(string $id) { // return view("user", ["id" => $id]); return view("user", compact("id")); } public function showBlog() { return view("blog"); } }
web.php Route::get("/", [PageController::class, 'showHome'])->name('home'); // route group Route::controller(PageController::class)->group(function () { Route::get("/", 'showHome')->name('home'); Route::get("/blog", 'showBlog')->name('blog'); Route::get("/user/{id}", 'showUser')->name('user'); });
- Single Action Controller
php artisan make:controller TestingController --invokable or php artisan make:controller TestingController --i class TestController extends Controller { public function __invok () { return view('test'); } } Route::get('/test', TestingController::class);
- myProject>php artisan route:list --except-vendor
- php artisan route:list --path=user
- Create Controller File
- To work on controller we should follow these three steps
- How to Work with Database
- Create Database
- Create Tables in Database(column Namw, Datatype)
- Insert Initial Data in Tables
- Code with Database
- Create Database
- Create Database Migration
- (Create tables in database)
- Seeding
- (Insert Initial Data in Tables)
- php artisan make:migration create_students_table
- Create Model
- CHAR(size)
- VARCHAR (size)
- BINARY(size)
- VARBINARY(size)
- TINYTEXT
- TEXT(size)
- MEDIUMTEXT
- LONGTEXT
- TINYBLOB
- BLOB(size)
- MEDIUMBLOB
- LONGBLOB
- ENUM(val1, val2, val3, ...)
- SET(vall, val2, val3,..)
- BIT(size) 1to64
- TINYINT(size) -128 to 127
- INT(size) -2147483648 to 2147483647
- INTEGER(size)
- SMALLINT(size) -32768 to 32767
- MEDIUMINT(size) -8388608 to 8383607
- BIGINT(size) -9223372036854775808 to 1. 9223372036854775807
- BOOL
- BOOLEAN 0/1
- FLOAT(p)
- DOUBLE(size, d) 255.568
- DECIMAL(size, d) size = 60, d = 30
- DEC(size,d)
- php artisan make:migration
- php artisan make:migration create_students_table / tablename
- php artisan migrate
- php artisan migrate:status
- php artisan migrate:rollback
- php artisan migrate:reset
- php artisan migrate:refresh
- php artisan migrate:fresh
- php artisan make:model Task -m
- Types of Modifications
- Column Modifications
- Add New Column
- Rename Column
- Delete Column
- Change Column Order
- Change Datatype or Size of Column
- Table Modifications
- Rename Table
- Delete Table
- Column Modifications
$table->renameColumn(‘from’, 'to');
MySQL <8.0.3
MariaDB < 10.5.2
$table->dropColumn('city');
$table->dropColumn(['city’, ‘avatar’, 'location']);
$table->string('name', 50)->change();
$table->integer('votes')->unsigned()->default(1)->comment('my comment')->change();
Change Column Order
$table after('password’, function (Blueprint $table) {
$table->string('address');
$table->string('city');
});
- NOT NULL
- UNIQUE
- DEFAULT
- PRIMARY KEY
- FOREIGN KEY
- CHECK
Stable->string(‘email')->nullable();
Stable->string(‘'email')->unique();
Stable->unique('email’);
Stable->string('city')->default('Agra');
Stable->primary('user_id');
Stable->foreign('user_id')->references('id')->on('users');
DB::statement('ALTER TABLE users ADD CONSTRAINT age CHECK (age > 18);');
Modifier | Description |
---|---|
->after('column’) | Place the column "after" another column (MySQL). |
->autoIncrement() | Set INTEGER columns as auto-incrementing (primary key). |
->comment('my comment’) | Add a comment to a column (MySQL/PostgreSQL). |
->first() | Place the column "first" in the table (MySQL). |
->from(Sinteger) | Set the starting value of an auto-incrementing field (MySQL / PostgreSQL). |
->invisible() | Make the column "invisible" to SELECT * queries (MySQL). |
->unsigned() | Set INTEGER columns as UNSIGNED (MySQL). |
->useCurrent() | Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value. |
->useCurrentOnUpdate() | Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated (MySQL). |
// create primary key
$table->primary('Cid');
// create foreign key
$table->foreign('city')->references('Cid')->on('City');
- Foreign Key with Cascade
Stable->foreign('City_id')->references('Cid')->on('City’)
->onUpdate('cascade')
->onDelete('cascade’);
cascadeOnUpdate();
cascadeOnDelete();
restrictOnUpdate();
restrictOnDelete();
nullOnDelete();
- 3way to make foreign key
$table->foreign('stu_id')->references('id')->on('students');
$table->foreignId('stu_id')->constrained (‘students’);
$table->unsignedBiginteger('student_id');
$table->foreignId('student_id')->constratined();
- Drop key Constraints
- php artisan make:migration update_library_table --table=libraries
- php artisan migrate:refresh
$table->dropPrimary('users_id_primary');
$table->dropUnique('users_email_unique');
$table->dropForeign('posts_user_id_foreign');
$table->dropForeign(['user_id']);