Skip to content

Instantly share code, notes, and snippets.

@subrotoice
Last active March 17, 2023 05:16
Show Gist options
  • Save subrotoice/e0738c40dae8c4ad4ce1c5786e6a1330 to your computer and use it in GitHub Desktop.
Save subrotoice/e0738c40dae8c4ad4ce1c5786e6a1330 to your computer and use it in GitHub Desktop.
https://docs.google.com/document/d/10_wKI-IB-O5DotEliyMJDe9SWdx2zWTuu_B7PcIQdCw
(Laravel Crash Course) youtube.com/watch?v=MFh0Fd7BsjE
youtu.be/xIApzP4mWyA
Naming Con: https://xqsit.github.io/laravel-coding-guidelines/docs/naming-conventions
Installation-----VS Code, Wamp, Composer, Laravel---
composer global require laravel/installer // Just Once,
laravel --version // 4.1.0 above Must have
IF any porblem then
# uninstall the package
composer global remove laravel/installer
# reinstall
composer global require laravel/installer
Create from existing one---- (First you need to run this -> composer global require laravel/installer)
laravel new myblog // myblog folder will autometically created
Direct Dowlnoad and create porject:
composer create-project --prefer-dist laravel/laravel myblog // Direct Download. Make sure composer installed by >>composer command
composer create-project laravel/laravel example-app // Also Work
# Set up Downloaded old project from git-----
https://devmarketer.io/learn/setup-laravel-project-cloned-github-com
https://www.youtube.com/watch?v=D5MZaCmpxvM
Step:
1. Download or clone project
2. Go to the folder application using cd
3. Run "composer install" // to install dependencies and create vendor folder inside your app
4. Copy .env.example file to .env on root folder.
You can type copy .env.example .env if using command prompt Windows
5. Open your .env file and change the database name (DB_DATABASE)
6. Run php artisan key:generate
7. Run php artisan migrate
8. Run php artisan serve
php artisan serve //By default the HTTP-server will listen to port 8000.
php artisan serve --port=8080
php artisan list // Listing All Available Commands
php artisan help migrate // HELP php artisan help make:controller
php artisan --version/php artisan -v
php --version/php -v // PHP version
------End Basics------
# Route, Empower yourself- https://www.youtube.com/watch?v=QWO1YPp0Hz4 -------------------
Route::get('/greeting', function () {
return 'Hello World'; // Direct String printing, ie. Underconstgruction
});
Route::get('/', function () { // calling view is form Controller
return view('welcome');
}); // Calling view directly, also do it by Route::view('/', 'welcome'); // calling welcome.blade.php
Route::get('/', 'SubrototestController@index'); // v-7 Style, calling controller and function index then you can call view through controller
Route::get('/', [SubrototestController::class, 'index']); // v-8 style, call index function in SubrototestController
Route::resource('/products', ProductController::class); //resourch function creates get(), post(), put(), patch(), delete()
return view('subroto'); // calling view form controller
Route::view('/welcome', 'welcome'); // Calling view directly form Route
Route::view('/welcome', 'welcome', ['name' => 'Taylor']); // Argument: 1. URI, 2. ViewName, 3. Array as argument (Array always: Laravel e built in function e value pss korar jonno always)
#middleware use, if not login then take to login page
Route::get('home2', function () {
echo "This is Home page22";
})->middleware('auth');
Route::resource('products', ProductController::class); // resourch function creates get(), post(), put(), patch(), delete()
Route::get('/test/{id}/{name}', function($id, $name) { // Variable is passing in URL must {}
echo "Good " . $name. $id;
});
Route::get('/test/{id?}/{name?}', function ($id='', $name=null){ // Optional Variabl passing
return view('myView', array('id' => $id, 'name' => $name));
});
Route::get('/posts/{post?}/comments/{comment?}', function (string $post='', string $comment='') { // in certain pattern
return view('myView', array('post' => $post, 'comment' => $comment));
});
Route::get('/ctest', function() {
$customers = Customer::all(); // Here Customer object, Fetch db data
echo "<pre>";
print_r($customers->toArray()); // Good way of debugging, object to array, you can use var_dump(), dd(), print_r() best
});
use App\Http\Controllers\UserController; // Calling controller in laravel 8 (in route>web.php file)
Route::get('/user', [UserController::class, 'index']); // Error: use App\Http\Controllers\NameOfController;
or Route::get('/', 'App\Http\Controllers\subrotoController@index'); // laravel 7 style || https://www.youtube.com/watch?v=MfE1tnMG6fE
------End Route------
# Controller -------------------------
php artisan make:controller subrototest2
php artisan make:controller subrototest3 -r // With CRUD ready, Later on you can create other functions like one(), two() for parposes
https://github.com/subrotoice/Laravel-CRUDs-3Projects/blob/main/README.md // All(7) functions of Controller
php artisan make:controller auth\RegisterController // Create directory auth and RegisterController
------End Controller------
# View - Blade template ------------------------
{{ $name }} = <?php echo $name; ?> //variable echo korar jonno
{{$name ?? 'Gaust'}} // name na thakle Gaust echo korbe, Conditional operator
{!! $demo !!} // HTML Print kore $demo = <h1>Jami</h1> same as {{}}, but it execute HTML attribute
@php @endphp, @if @endif, @for @endfor, @foreach @endforeach
@foreach($countries as $key=>$countrie)
<option value="{{$key}}">{{$countrie}}</option>
@endforeach
{{-- Comment --}}, {{--Comment--}} // Same Work
// Main layout, Folder er modde thakle "." use korte hoy
@include('layout.head') // file name head.blade.php , @include(layout.head) - "layout" folder in view
@yield('main-content') // Creating place for taking element from landing page
@include('layout.footer')
# Landing Page Content
@extends('layout.app')
@section('main-content') // Pushing element to parent
<h1>Home Page</h1>
@endsection
#By this block you can push any code to parent balde
@stack('title_name') // In parent blade
@push('title_name')// in Child blade
<title>Home Title</title>
@endpush
------End View------
# Model -----Database talk--------------
php artisan make:model subroto1 //normal model creating, Add- protected $fillable = ['name', 'age'];
php artisan make:model subroto3 -mc // model with Migration made and Controller
php artisan make:model subroto5 -mcr // With CRUD, Best! from my Opinion
php artisan make:model Subroto6 -mcr --factory // model with Rrsource Controller, Migration and Factory
# Migration ----Schema -> DB Table -------------------
# IF migrate not work properly, Edit your AppServiceProvider.php on App\Providers\AppServiceProvider file
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
php artisan cache:clear // after change environment
php artisan config:cache // After change .env
// Migration e je je property thakbe ta DB Table e asbe, Model er property DB Table e kichu asbe na
php artisan migrate // Schema -> DB Table, NB: Restart server after Migrate. 1. Ctrl+C, 2. php artisan serve, Error asbe so add below code
php artisan migrate:rollback // roll back the last batch of migrations
php artisan migrate:reset // delete data+Table, Very Careful | roll back all the migrations
php artisan migrate:fresh // Drop and Recreate
# Seeder, Autometically Fill hoy data, Pagination, Delete, Update, edit chaeck korete easy hoy, manual entry lage na
php artisan make:model Customer -mcr
php artisan migrate
php artisan make:seeder CustomerSeeder
// in CustomerSeeder, use App\Models\Customer; (Random number instade of Faker class) https://prnt.sc/1bcygEkp6dLW
$faker = Faker::create();
for($i=1; $i<=100; $i++) {
$customer = new Customer();
$customer->name = rand();
$customer->email = rand().'@gmail.com';
$customer->address = rand();
$customer->save();
}
// Using Faker, Feel like real information, in CustomerSeeder, use App\Models\Customer; use Faker\Factory as Faker;
$faker = Faker::create();
for($i=1; $i<=100; $i++) {
$customer = new Customer();
$customer->name = $faker->name;
$customer->email = $faker->email;
$customer->address = $faker->address;
$customer->save();
}
// In DatabaseSeeder, in public function run(): void paste this code
$this->call([
CustomerSeeder::class
]);
- php artisan db:seed // Seeding.... Check your database Bro, This command invoke upper code
NB: Faker is one kind of random number in Formated Manner, You can use in anywhere ie. controller - https://prnt.sc/1V8Zcv7cfRfw
More Data type: https://github.com/fzaninotto/Faker
// Another way of seeding (https://dev.to/olodocoder/laravel-seeding-generate-mock-data-using-faker-5473)
php artisan make:model Subroto7 -mcr --factory // Resource Controller, Migration, Factory
public function up(): void // in migration/subroto7s
{
Schema::create('subroto7s', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->longText('body');
$table->string('author');
$table->integer('likes');
$table->boolean('draft');
$table->timestamps();
});
}
// Factories/Subroto7Factory
return [
'title' => $this->faker->words(5, true),
'body' => $this->faker->sentence(45),
'likes' => $this->faker->randomNumber(5),
'author' => $this->faker->name(),
'draft' => $this->faker->boolean()
];
// seeders/DatabaseSeeder.php in run()
\App\Models\Subroto7::factory(14)->create();
php artisan migrate:fresh --seed // Seeding... Done! // php artisan migrate --seed previous 14 data thakle again 14 data add hobe
$customers = Customer::latest()->get(); // In Controller (all rows), use App\Models\Customer; but not need $customer = new Customer()
$customers = Customer::latest()->paginate(2); //pagination
return view('customers', ['customers'=> $customers]); // call view with data, in Controller
@foreach($customers as $customers) // in customer.blade.php
<h1>{{$customers->id}} {{$customers->title}}</h1> {{$customers->body}}
@endforeach
return view('support', ['foo'=>'Subroto', 'go'=>'Goutom']); // Passing values
<h2>{{$foo}}</h2> // Desplaying data in view. "$" is must
<ul> // show all data {{ $variable }} Style
@foreach($projects as $project)
<li>
<a href="/db/{{$project->id}}"><h3>{{$project->title}}</h3></a>
{{$project->body}}
</li>
@endforeach
</ul>
{{$projects->links()}} //pagination with links, also call in controller
<h1>{{$project->title}}</h1> // For single data
<p>{{$project->body}}</p>
use Illuminate\Support\Facades\DB; // for using database, https://laravel.com/docs/10.x/queries
$dataAll = DB::table('subroto5s')->get(); // subroto5s is table name, https://laravel.com/docs/8.x/queries
dd($dataAll); // Display like var_dump()
$dataAll = DB::table('subroto5s')
->where('id', '>', 2)
->orderBy('id', 'asc')
->get();
$email = DB::table('users')->where('name', 'John')->value('email'); // Get only email as string
DB::table('subrotodbs')->select('name', 'city as myCity')->get(); // show only two column
# Row Query
$results = DB::select('select * from users where id = :id', ['id' => 1]);
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
$affected = DB::delete('delete from subrotodbs where name = ?', ['five']);
composer require laravel/ui "^2.0" // Auth installation (Login, register, forget pass)
php artisan ui vue --auth
npm install && npm nun dev
php artisan route:list // to see routes
# API ------- https://www.youtube.com/playlist?list=PLbC4KRSNcMnoQONzuNtFlhEzegTYadoBY
public function boot()
{
Schema::defaultStringLength(191); // add this in app/porvides/ServiceProvider.php
}
use App\Http\Controllers\Api\mycalssController; // in route/api.php
Route::apiResource('/class', mycalssController::class);
# Crud
public function index()
{
$classes = DB::table('myclasses')->get(); // Read, api could be checked by- http://127.0.0.1:8000/api/subroto, or Postman
return response()->json($classes); // Postman download: https://www.postman.com/downloads
}
$validatedData = $request->validate([
'class_id' => 'required',
'subject_name' => 'required|unique:subjects|max:25',
'subject_code' => 'required|max:25'
]);
$Subject = Subject::create($request->all()); // Create, in store()
# Show($id), only one -----
$subroto = DB::table('subrotodbs')->where('id', $id)->first(); // Query Bilder, show with id, /student/1, in show($id)
echo $subroto->city;
$subject = Subject::findorfail($id); // Eloquent Model Same thing of upper first() call
#update ------
$subject = Subject::findorfail($id);
$subject->update($request->all()); // Update, in update()
#Eloquent Model ORM --------
Eloquent Benefits: 1. Easy CRUD, 2. Relationship Building (Object and Relation Mapping)
Subrotodb::all(); // "subrotodb" model, use\Models\subrotodb
subrotodb::where('name', 'one') // May use query bilder
->orderBy('name', 'asc')
->take(3)
->get();
#Search ------------
$subrotos = Subrotodb::find($id); // Search
$subrotos = Subrotodb::findOrFail($id);
$subrotos = Subrotodb::where('id', '>', 5)->firstOrFail();
# insert ---------
$subrotodb = new Subrotodb; // Insert
$subrotodb->name = 'six';
$subrotodb->city = 'DInajpur';
$subrotodb->save(); //created_at and updated_at timestamps will automatically be set
# Update --------------
$subrotodb = Subrotodb::find(6); // Updated
$subrotodb->name = 'Dinajpur';
$subrotodb->save();
# Delete -----------
$Subrotodb = Subrotodb::find(6);
$Subrotodb->delete();
# Delete alternative -------
Subrotodb::destroy(4);
Subrotodb::destroy(1, 2, 3); // delete all with id 1, 2, 3
Subrotodb::where('id', '<', 10)->delete();
class User {
public function stories() {
return $this->hasMany('App\Story');
}
}
public function user() {
return $this->belongsTo('app\User');
}
Now the benefit of defining the Eloquent ORM relationship is that,
once you have a user you can access all stories by this relationship. You need not to write any other queries.
# Authenticatoin- 3 methods- UI, Fortify, JetStrime
Autometically create login, register, logout, forget
composer require laravel/ui // https://github.com/laravel/ui
php artisan ui bootstrap --auth // or php artisan ui vue --auth
npm install && npm run dev ( Check Node.js install machine node -v, npm -v )
// Then 'php artisan serve' check login and registration come
# Fortify Authentication-- https://www.youtube.com/watch?v=NuGBzmHlINQ , https://github.com/laravel/fortify
composer require laravel/fortify // here need to copy css, js, view file manually
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan migrate
Create model with migaraton, Every table associated with model, Migration is vertion controller for that table
php artisan make:model Story -m
# Tinker-------------
php artisan tinker
>>> $user->stories
>>> $user->stories();
=> Illuminate\Database\Eloquent\Relations\HasMany {#3079}
>>> $user->stories->first()
>>> $user->stories->count()
>>> App\Story::find(1)->user
>>> $user = App\Story::find(1)->user
>>> $user->name = "Goutom Biswas"
>>> $user->email = "goutom@gmail.com"
>>> $user->save()
>>> $user = App\Story::find(1)->user
>>> $user->stories()->create(['title' => 'Now Create', 'body'=>'This is body', 'type'=>'Very Short', 'status'=>0]);
// Here we don't insert user_id but laravel insert 1 as user_id for us
>>> App\Story::all()
Just go through: https://laravel.com/docs/5.0/eloquent#collections
$users = User::all(); // Model_Name::function_Name();
$user = User::find(1);
var_dump($user->name);
$users = User::where('votes', '>', 100)->take(10)->get();
foreach ($users as $user)
{
var_dump($user->name);
}
Eloquent Aggregates:
Of course, you may also use the query builder aggregate functions.
$count = User::where('votes', '>', 100)->count();
Deleting An Existing Model:
$user = User::find(1);
$user->delete();
$affectedRows = User::where('votes', '>', 100)->delete();
Note: All methods available on the query builder are also available when querying Eloquent models.
Project Work--
// $stories = Story::where('user_id', auth()->user()->id )
// ->orderBy('id', 'DESC')
// ->get(); // Query here
// Pagenate
$stories = Story::where('user_id', auth()->user()->id )
->orderBy('id', 'DESC')
->paginate(2); // Query here
{{ $stories->links() }} <!-- Pagination Links-->
Web request flow: Route>>Controller>>View>Model
@subrotoice
Copy link
Author

Gsf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment