├── .gitignore ├── .vscode └── settings.json ├── 1_introduction.php ├── 2_project_structure.php ├── 3_artisan_command.php ├── 4_configuration_and_environment_files.php ├── 5_routing.php ├── 6_middleware.php ├── 7_controllers.php ├── 8_blade_template_engine.php ├── 9_eloquent_orm.php ├── Lessons ├── 1_overview_of_laravel_and_its_benefits │ ├── assignment │ │ └── overview_of_laravel_and_its_benefits.js │ ├── lecture │ │ └── overview_of_laravel_and_its_benefits.js │ ├── quiz │ │ └── overview_of_laravel_and_its_benefits.js │ ├── short_question │ │ └── overview_of_laravel_and_its_benefits.js │ └── true_false │ │ └── overview_of_laravel_and_its_benefits.js └── 2_laravel_mvc_architecture │ ├── assignment │ ├── 1_portfolio_site.js │ ├── 2_blog_site.js │ ├── 3_todo_list_app.js │ └── laravel_mvc_architecture.js │ ├── coding_examples │ ├── 1_library.js │ └── 2_blog.js │ ├── lecture │ ├── 1_introduction_to_mvc.js │ ├── 2_explain_mvc.js │ ├── 3_advantage_of_mvc.js │ ├── 4_mvc_in_other_framework.js │ ├── 5_laravel_mvc_implementation.js │ ├── 6_how_laravel_implements_mvc_architecture.js │ ├── 7_the_roles_of_models_views_and_controllers_in_Laravel_applications.js │ └── 8_creation of models, views, and controllers.js │ ├── project_ideas │ └── list_of_project_idea.js │ ├── quiz │ └── laravel_mvc_architecture.js │ ├── short_question │ └── laravel_mvc_architecture.js │ └── true_false │ └── laravel_mvc_architecture.js ├── agenda.excalidraw ├── curriculum_laravel.js ├── feedback_on_assignment.js ├── laravel_concept ├── basic_concept.php ├── facades.php ├── illuminate.php ├── model.php ├── query_builder.php └── support.php ├── laravel_curriculum.php ├── laravel_final.php ├── lesson_plan ├── 1_overview_of_laravel_and_its_benefits.js ├── 2_laravel_mvc_architecture.js └── 3_setting_up_the_development_environment.js ├── slides_rabbil_bhai ├── Complete Client-Server Basics.pdf ├── Copy of 2 Laravel Request.pdf ├── Laravel Class 22 May.pdf ├── Laravel Migration (Module 16).pdf ├── Laravel Module 15.pdf ├── Laravel Query Builder (Module 17 Resource).pdf ├── Laravel Query Builder.pdf ├── Laravel Request.pdf ├── Laravel_rabbil_bhai_Module 14.pdf └── laravel_rabbil_bhai_module_13.pdf ├── test ├── about.php ├── contact.php ├── index.php └── recursion.php └── understanding_laravel ├── 10_http_request _nside.png ├── 11_http_request.png ├── 12_http_response.png ├── 13_request_response_life_cycle_laravel.png ├── 14_middlewares.png ├── 15_authentication_authorization.png ├── 16_authentication_authorization.png ├── 17_guard.png ├── 17_understanding_guard.js ├── 1_environment.png ├── 2_docker.png ├── 3_understanding_composer.js ├── 4_laravel_installation_command.js ├── 4_query_params_vs_path_variable.png ├── 5_dump_and_die.js ├── 6_kernel.png ├── 7_1_mvc_row.png ├── 7_mvc.png ├── 8_library_vs_framework.png ├── 9_reqest_response.png ├── eloquent_orm ├── 10_softdeletes.js ├── 11_pruning_model.js ├── 12_replicating_models.js ├── 13_global_scope.js ├── 14_local_scope.js ├── 15_dynamic_scope.js ├── 16_using_trait_to_store_scope.js ├── 1_introduction_to_eloquent_orm.js ├── 2_eloquent_model_conventions.js ├── 3_important_eloquent_model_conventions.js ├── 4_mass_assignment.js ├── 5_route_model_binding.js ├── 6_firstOrCreate_vs_firstOrNew_method.js ├── 7_Attribute_Changes_isDirty_isClean_wasChanged.js ├── 8_updateOrCreate_upsert.js ├── 9_delete_truncate_destroy.js ├── eloquent_orm.png └── note.js ├── eloquent_orm_2.png ├── hydration.png ├── model_migration_seeder_factory ├── apiResource.js ├── apiResourceRoute.js ├── factory.js ├── migration.js ├── model.js └── seeder.js ├── note.js ├── observer_design_pattern.png ├── php_premier ├── HasFactory_trait.js ├── trait.js ├── understanding_controller.js ├── understanding_guard.js ├── understanding_namespace.js ├── understanding_notifiable.js ├── understanding_policy.js ├── understanding_resource.js ├── understanding_routes.js └── understanding_softDeletes.js ├── pub_sub_pattern.png ├── qurey_builder ├── 1_query_builder_helper_methods.js ├── important_query_builder_methods.js ├── query_builder.js ├── query_builder_advance_topics │ ├── 10_removing_existing_ordering.js │ ├── 11_using_the_paginate_method.js │ ├── 12_using_the_simplePaginate_method.js │ ├── 13_using_the_cursorPaginate_method.js │ ├── 1_database_transactions.js │ ├── 2_pessimistic_locking.js │ ├── 3_chunking_data.js │ ├── 4_streaming_results_lazily.js │ ├── 5_raw_methods.js │ ├── 6_ordering_through_query_builder.js │ ├── 7_full_text_indexs.js │ ├── 8_limit_offset_through_query_builder.js │ └── 9_conditional_clause.js ├── query_builder_methods.js └── query_builder_methods_description.js ├── relationship ├── 1_one_to_one_relationship.png ├── 2_one_to_many_relationship.png ├── 3_many_to_many_relationship.png ├── 4_polymorphic_relationship.png ├── 5_define_relationship.js ├── 6_foreignkey.png ├── 7_one_to_one_relationship.js └── 8_one_to_many_relationship.js ├── request_response_lifecycle_in_laravel.js ├── routing_and_front_controller.png ├── sanctum └── understand_sanctum.js ├── service_container ├── dependency_injection.js ├── dependency_inversion_principle.js ├── inversion_of_control_principle.js ├── ioc_container.js ├── reflection.js ├── service_container.js └── service_provider.js ├── templating.png ├── understanding laravel concepts.png ├── understanding_factory_seeder └── factory.js ├── understanding_laravel_concepts.excalidraw ├── understanding_migration ├── note_for_migration.js └── table_methods.js └── who_is_better_developer.png /.gitignore: -------------------------------------------------------------------------------- 1 | prompts -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "Laravel", 4 | "phpfmt", 5 | "trunacte" 6 | ] 7 | } -------------------------------------------------------------------------------- /1_introduction.php: -------------------------------------------------------------------------------- 1 | = 7.3 8 | // Composer (a dependency management tool for PHP) 9 | // Once you have the prerequisites, you can install Laravel using Composer. Open your terminal or command prompt and run the following command: 10 | 11 | 12 | // composer global require laravel/installer 13 | // This will install the Laravel installer globally on your system. Now, you can create a new Laravel project using the following command: 14 | 15 | 16 | // laravel new project-name 17 | // Replace "project-name" with the desired name for your project. This will create a new folder with the project files in it. 18 | 19 | // Now, let's cover some basic concepts in Laravel: 20 | 21 | // Routes: Routes define the URLs of your application and map them to a specific function or method in a controller. In Laravel, you can define routes in the routes/web.php file. For example, to create a route for the homepage: 22 | 23 | // Route::get('/', function () { 24 | // return view('welcome'); 25 | // }); 26 | // Controllers: Controllers are responsible for handling user requests and returning a response. To create a controller, run the following command: 27 | 28 | // php artisan make:controller ControllerName 29 | // Replace "ControllerName" with the desired name for your controller. 30 | 31 | // Models: Models represent the data structure of your application and are used to interact with the database. To create a model, run the following command: 32 | 33 | // php artisan make:model ModelName -m 34 | // Replace "ModelName" with the desired name for your model. The -m flag creates a migration file for the model. 35 | 36 | // Views: Views are the templates that render the HTML of your application. Laravel uses the Blade templating engine, which allows you to write clean and easy-to-read templates. Views are stored in the resources/views directory. 37 | 38 | // Migrations: Migrations are like version control for your database. They allow you to modify your database schema in a structured and organized way. Migrations are stored in the database/migrations directory. 39 | 40 | // Artisan: Laravel includes a command-line tool called Artisan, which provides useful commands for common tasks. To see a list of available commands, run: 41 | 42 | 43 | // php artisan list 44 | 45 | // This should give you a basic understanding of Laravel and its structure. As you continue to learn and work with Laravel, you will encounter more advanced features and concepts, such as Eloquent ORM, Middleware, Service Providers, and more. There are numerous resources available online to help you deepen your understanding and improve your skills with Laravel. 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /2_project_structure.php: -------------------------------------------------------------------------------- 1 | belongsToMany(User:: class) -> withPivot('borrowed_at', 'returned_at'); 20 | // } 21 | // } 22 | 23 | 24 | // belongsToMany(Book:: class) -> withPivot('borrowed_at', 'returned_at'); 35 | // } 36 | // } 37 | 38 | // Note that we've defined a many-to-many relationship between the Book and User models using the belongsToMany() method. This is because each user can borrow multiple books, and each book can be borrowed by multiple users. We've also included a withPivot() method to specify the additional fields we'll need in the pivot table (which we'll create later). 39 | 40 | // Views 41 | // We'll need several views for this application: 42 | 43 | // A view to display the list of available books. 44 | // A view to display the details of a single book. 45 | // A view to display the list of borrowed books for a specific user. 46 | // A view to allow a user to borrow a book. 47 | // A view to allow a user to return a book. 48 | // Here's an example of what the view to display the list of available books might look like (books/index.blade.php): 49 | 50 | 51 | 52 | // @extends ('layouts.app') 53 | 54 | // @section('content') 55 | //

Available Books

56 | 57 | // 65 | // @endsection 66 | 67 | 68 | 69 | // Controllers 70 | // We'll need several controllers for this application as well: 71 | 72 | // A controller to handle the list of available books. 73 | // A controller to handle the details of a single book. 74 | // A controller to handle the list of borrowed books for a specific user. 75 | // A controller to handle the borrowing of a book. 76 | // A controller to handle the returning of a book. 77 | // Here's what the controller to handle the list of available books might look like (BookController.php): 78 | 79 | 80 | // get(); 90 | 91 | // return view('books.index', compact('books')); 92 | // } 93 | 94 | // public function show(Book $book) { 95 | // return view('books.show', compact('book')); 96 | // } 97 | // } 98 | 99 | 100 | // In this example, we've defined two methods: index() and show(). The index() method retrieves a list of available books from the database (i.e., books where the available field is true) using the where() method on the ` 101 | 102 | 103 | 104 | 105 | // Copy to Clipboard 106 | 107 | // Raihana Ferdousi 108 | // please complete the sentence.please exclude what you have already stated above 109 | // Sure, in the index() method on the BookController, we've also passed the retrieved list of books to the index.blade.php view using the compact() function. Similarly, in the show() method, we've passed a single book object to the show.blade.php view using the compact() function. 110 | 111 | 112 | 113 | 114 | // Copy to Clipboard 115 | 116 | -------------------------------------------------------------------------------- /Lessons/2_laravel_mvc_architecture/coding_examples/2_blog.js: -------------------------------------------------------------------------------- 1 | // present a scenario of a simple web application like a blog to design an MVC - based architecture for their application, including the models, views, and controllers needed 2 | // Sure, let's consider the scenario of a simple blog web application. We can break down the application into three main components: the models, views, and controllers. 3 | 4 | // Models: 5 | 6 | // In this scenario, we will need at least two models: Post and Category.The Post model will represent the blog posts, and the Category model will represent the categories to which a post belongs. 7 | 8 | // Here's an example of what the Post model might look like: 9 | 10 | // php 11 | // Copy code 12 | // belongsTo(Category:: class); 23 | // } 24 | // } 25 | // And here's an example of what the Category model might look like: 26 | 27 | // php 28 | // Copy code 29 | // hasMany(Post:: class); 40 | // } 41 | // } 42 | // Views: 43 | 44 | // In this scenario, we will need at least two views: index.blade.php and show.blade.php.The index.blade.php view will display a list of all the blog posts, and the show.blade.php view will display the details of a single blog post. 45 | 46 | // Here's an example of what the index.blade.php view might look like: 47 | 48 | // html 49 | // Copy code 50 | // < !--resources / views / posts / index.blade.php-- > 51 | 52 | // @extends ('layouts.app') 53 | 54 | // @section('content') 55 | //

Blog Posts

56 | 57 | // 62 | // @endsection 63 | // And here's an example of what the show.blade.php view might look like: 64 | 65 | // html 66 | // Copy code 67 | // < !--resources / views / posts / show.blade.php-- > 68 | 69 | // @extends ('layouts.app') 70 | 71 | // @section('content') 72 | //

{{ $post->title }}

73 | 74 | //

{{ $post->body }}

75 | 76 | //

Category: {{ $post->category->name }}

77 | // @endsection 78 | // Controllers: 79 | 80 | // In this scenario, we will need at least one controller: PostController.The PostController will handle the HTTP requests and responses for the blog posts. 81 | 82 | // Here's an example of what the PostController might look like: 83 | 84 | // php 85 | // Copy code 86 | // 'mysql', 17 | 18 | 'connections' => [ 19 | 20 | 'mysql' => [ 21 | 'driver' => 'mysql', 22 | 'host' => 'localhost', 23 | 'database' => 'my_database', 24 | 'username' => 'my_username', 25 | 'password' => 'my_password', 26 | 'charset' => 'utf8mb4', 27 | 'collation' => 'utf8mb4_unicode_ci', 28 | 'prefix' => '', 29 | 'strict' => true, 30 | 'engine' => null, 31 | ], 32 | 33 | ], 34 | 35 | ]; 36 | Then, in your code, you can use the DB facade to interact with the database: 37 | 38 | php 39 | Copy code 40 | get(); 52 | 53 | foreach ($users as $user) { 54 | echo $user->name; 55 | } 56 | } 57 | } 58 | In this example, we are using the get() method to retrieve all records from the users table, and then looping through the results to output each user's name. 59 | 60 | Note that you can also use Illuminate's ORM, Eloquent, to interact with the database. Eloquent provides a more expressive and intuitive syntax for working with database records, and includes features like model relationships and attribute casting. Here is an example of using Eloquent: 61 | 62 | php 63 | Copy code 64 | name; 93 | } 94 | } 95 | } 96 | In this example, we are using the all() method to retrieve all records from the users table using the User model. The syntax for querying the database using Eloquent is similar to using the DB facade, but provides additional features and a more expressive syntax. 97 | 98 | 99 | 100 | 101 | 102 | 103 | */ -------------------------------------------------------------------------------- /laravel_concept/model.php: -------------------------------------------------------------------------------- 1 | sayHello(); 13 | 14 | if($_SERVER['REQUEST_URI']==="/about"){ 15 | require("./about.php"); 16 | }else if($_SERVER['REQUEST_URI']==="/contact"){ 17 | require("./contact.php"); 18 | }else{ 19 | 20 | echo "Hello"; 21 | } 22 | -------------------------------------------------------------------------------- /test/recursion.php: -------------------------------------------------------------------------------- 1 | 5){ 6 | return; 7 | } 8 | 9 | 10 | recur($value+1); 11 | echo $value.PHP_EOL; 12 | 13 | }; 14 | 15 | recur(1); -------------------------------------------------------------------------------- /understanding_laravel/10_http_request _nside.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/10_http_request _nside.png -------------------------------------------------------------------------------- /understanding_laravel/11_http_request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/11_http_request.png -------------------------------------------------------------------------------- /understanding_laravel/12_http_response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/12_http_response.png -------------------------------------------------------------------------------- /understanding_laravel/13_request_response_life_cycle_laravel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/13_request_response_life_cycle_laravel.png -------------------------------------------------------------------------------- /understanding_laravel/14_middlewares.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/14_middlewares.png -------------------------------------------------------------------------------- /understanding_laravel/15_authentication_authorization.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/15_authentication_authorization.png -------------------------------------------------------------------------------- /understanding_laravel/16_authentication_authorization.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/16_authentication_authorization.png -------------------------------------------------------------------------------- /understanding_laravel/17_guard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/17_guard.png -------------------------------------------------------------------------------- /understanding_laravel/17_understanding_guard.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, guards are used for authentication and determine how users are authenticated for different parts of your application. Guards define the sources from which authentication information should be retrieved, such as databases, API tokens, or sessions. 3 | 4 | The most common guard used in Laravel is the web guard, which provides session-based authentication. Let's take a look at an example to understand how to use guards in Laravel. 5 | 6 | First, let's assume you have a User model and a users table in your database. 7 | 8 | Define the Guard Configuration: 9 | Open the config/auth.php file in your Laravel project. You will find an array of guards defined in this file. By default, Laravel comes with the web guard pre-configured. You can add additional guards as needed. Here's an example of how you can define a guard named admin: 10 | 11 | 'guards' => [ 12 | 'web' => [ 13 | 'driver' => 'session', 14 | 'provider' => 'users', 15 | ], 16 | 17 | 'admin' => [ 18 | 'driver' => 'session', 19 | 'provider' => 'admins', 20 | ], 21 | ], 22 | Define the Provider Configuration: 23 | The next step is to define the provider for the guard. Providers determine how the user information should be retrieved. In our example, let's create a users provider for the web guard and an admins provider for the admin guard. Open the config/auth.php file again and define the providers: 24 | 25 | 'providers' => [ 26 | 'users' => [ 27 | 'driver' => 'eloquent', 28 | 'model' => App\Models\User::class, 29 | ], 30 | 31 | 'admins' => [ 32 | 'driver' => 'eloquent', 33 | 'model' => App\Models\Admin::class, 34 | ], 35 | ], 36 | 37 | Protect Routes using Guards: 38 | Now that you have defined the guards and providers, you can protect your routes using the desired guard. In your routes file (web.php or api.php), you can use the middleware method to apply the guard. Here's an example that protects a route group with the admin guard: 39 | 40 | Route::middleware('auth:admin')->group(function () { 41 | // Routes that require admin authentication 42 | Route::get('/admin/dashboard', 'AdminController@dashboard'); 43 | Route::get('/admin/users', 'AdminController@users'); 44 | }); 45 | In this example, the auth:admin middleware ensures that only authenticated administrators can access the routes within the group. 46 | 47 | Logging In and Authenticating Users: 48 | To log in users, you can use the Auth facade in Laravel. Here's an example of logging in a user using the web guard: 49 | 50 | use Illuminate\Support\Facades\Auth; 51 | 52 | if (Auth::guard('web')->attempt(['email' => $email, 'password' => $password])) { 53 | // User authentication successful 54 | return redirect()->intended('/dashboard'); 55 | } else { 56 | // User authentication failed 57 | return redirect()->back()->withErrors(['message' => 'Invalid credentials']); 58 | } 59 | In this example, we are using the attempt method on the Auth facade to attempt user authentication based on the provided email and password. 60 | 61 | That's a basic overview of using guards in Laravel. By defining guards, providers, and protecting routes, you can control authentication and authorization within your application. Remember to customize the code examples based on your specific application requirements and user model. 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | */ -------------------------------------------------------------------------------- /understanding_laravel/1_environment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/1_environment.png -------------------------------------------------------------------------------- /understanding_laravel/2_docker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/2_docker.png -------------------------------------------------------------------------------- /understanding_laravel/4_query_params_vs_path_variable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/4_query_params_vs_path_variable.png -------------------------------------------------------------------------------- /understanding_laravel/5_dump_and_die.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, dd() is a debugging function that stands for "Dump and Die". When you call dd() in your code, Laravel will dump the contents of a variable or expression to the screen and then stop the execution of the script. This can be useful for debugging and inspecting variables and values at different stages of your code execution. 3 | 4 | For example, suppose you have a variable $users that contains an array of user objects. You could call dd($users) to dump the contents of this array to the screen and see what data it contains. The output of dd($users) would be displayed in your browser or console window, and would look something like this: 5 | 6 | 7 | array:3 [ 8 | 0 => array:2 [ 9 | "name" => "John" 10 | "email" => "john@example.com" 11 | ] 12 | 1 => array:2 [ 13 | "name" => "Jane" 14 | "email" => "jane@example.com" 15 | ] 16 | 2 => array:2 [ 17 | "name" => "Bob" 18 | "email" => "bob@example.com" 19 | ] 20 | ] 21 | The dd() function can also take multiple arguments, allowing you to dump multiple variables or expressions at once. For example, you could call dd($users, $request->input('search')) to dump both the contents of the $users variable and the value of the search input field in a request. 22 | 23 | In summary, dd() is a useful debugging function in Laravel that allows you to quickly inspect the contents of variables and expressions in your code. 24 | */ 25 | 26 | /* 27 | var_dump("abcd"); 28 | die(); 29 | dd("abcd"); 30 | 31 | */ -------------------------------------------------------------------------------- /understanding_laravel/6_kernel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/6_kernel.png -------------------------------------------------------------------------------- /understanding_laravel/7_1_mvc_row.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/7_1_mvc_row.png -------------------------------------------------------------------------------- /understanding_laravel/7_mvc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/7_mvc.png -------------------------------------------------------------------------------- /understanding_laravel/8_library_vs_framework.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/8_library_vs_framework.png -------------------------------------------------------------------------------- /understanding_laravel/9_reqest_response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/9_reqest_response.png -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/10_softdeletes.js: -------------------------------------------------------------------------------- 1 | // 👉softDeletes, withTrashed(), restore(), and forceDelete() in Laravel's Eloquent ORM. 2 | 3 | // These features are related to handling soft deletes, which allow you to "softly" delete records from the database without actually removing them permanently. 4 | 5 | // SoftDeletes: 6 | // The SoftDeletes trait is used to add soft delete functionality to your Laravel Eloquent models.By including this trait in a model, you enable the soft delete behavior, meaning that records are marked as deleted instead of being physically deleted from the database. 7 | // To use soft deletes, follow these steps: 8 | 9 | // Step 1: Add the deleted_at column to your table.This column will store the deletion timestamp.You can create a migration to add this column using the following command: 10 | 11 | 12 | // php artisan make:migration add_deleted_at_column_to_table--table = your_table_name 13 | // Inside the generated migration file, add the deleted_at column: 14 | 15 | 16 | // public function up() { 17 | // Schema:: table('your_table_name', function (Blueprint $table) { 18 | // $table -> softDeletes(); 19 | // }); 20 | // } 21 | // Step 2: In your Eloquent model, use the SoftDeletes trait and specify the deleted_at column: 22 | 23 | 24 | // use Illuminate\Database\Eloquent\Model; 25 | // use Illuminate\Database\Eloquent\SoftDeletes; 26 | 27 | // class YourModel extends Model { 28 | // use SoftDeletes; 29 | 30 | // protected $dates = ['deleted_at']; 31 | // } 32 | // With these steps, when you call the delete () method on a model instance, it will be soft deleted by setting the deleted_at column to the current timestamp. 33 | 34 | // withTrashed(): 35 | // The withTrashed() method is used to retrieve both the non - deleted and soft - deleted records from a table.By default, Laravel's queries exclude soft-deleted records. However, you can include them in your queries using withTrashed(). 36 | // Here's an example: 37 | 38 | 39 | // $records = YourModel:: withTrashed() -> get(); 40 | // In the above code, the withTrashed() method is called before get(), which retrieves all records, including the soft - deleted ones. 41 | 42 | // restore(): 43 | // The restore() method is used to restore a soft - deleted record.Once a record is soft deleted, you can use restore() to bring it back to the active state. 44 | 45 | // $record = YourModel:: withTrashed() -> find($id); 46 | // $record -> restore(); 47 | // In the above code, find($id) retrieves the soft - deleted record with the given ID, and restore() restores it. 48 | 49 | // forceDelete(): 50 | // The forceDelete() method is used to permanently delete a soft - deleted record from the database.Unlike delete (), which performs a soft delete, forceDelete() removes the record entirely. 51 | 52 | // $record = YourModel:: withTrashed() -> find($id); 53 | // $record -> forceDelete(); 54 | // In the above code, find($id) retrieves the soft - deleted record, and forceDelete() removes it permanently. 55 | 56 | // That covers the basic usage of soft deletes and related methods in Laravel's Eloquent ORM. Remember to include the SoftDeletes trait in your models, specify the deleted_at column, and use the provided methods to handle soft deletes as needed. 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/12_replicating_models.js: -------------------------------------------------------------------------------- 1 | //👉 Replicate models in Laravel's Eloquent ORM. 2 | 3 | // Replicating models can be useful when you need to create copies of existing database records.Let's dive into the details with code examples. 4 | 5 | // First, make sure you have Laravel installed and set up in your development environment.Once you have Laravel ready, follow these steps: 6 | 7 | // Step 1: Create a Model 8 | // Start by creating a model in Laravel using the php artisan make:model command.For example, let's create a User model: 9 | 10 | 11 | // php artisan make:model User 12 | // This command will create a User model file in the app / Models directory. 13 | 14 | // Step 2: Prepare the Database 15 | // Make sure you have a corresponding table in your database for the model you're working with. Laravel's Eloquent ORM assumes that the table name is the plural form of the model's name, with an "s" added by default. For example, the User model will correspond to the users table. If you need to customize the table name, you can do so in the model's $table property. 16 | 17 | // Step 3: Replicating a Model 18 | // To replicate a model, you can use the replicate method provided by Eloquent.The replicate method creates a new instance of the model and copies all the attributes from the original model. 19 | 20 | // Here's an example of how to replicate a User model: 21 | 22 | 23 | // $user = User:: find(1); // Retrieve the original model from the database 24 | // $newUser = $user -> replicate(); // Replicate the model 25 | 26 | // Optionally modify any attributes of the new model 27 | // $newUser -> name = 'John Doe'; 28 | // $newUser -> email = 'johndoe@example.com'; 29 | 30 | // $newUser -> save(); // Save the replicated model to the database 31 | // In the above example, we retrieve the original User model from the database using the find method.Then, we call the replicate method on the retrieved model to create a new instance with the same attribute values.Finally, we can modify any necessary attributes on the new model and save it to the database using the save method. 32 | 33 | // You can replicate models with relationships as well.The replicate method will also copy the relationships, but the related models will still reference the original models.If you need to duplicate the related models, you'll need to handle that separately. 34 | 35 | // That's the basic process for replicating models in Laravel's Eloquent ORM.You can adapt this approach for other models in your application. 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/13_global_scope.js: -------------------------------------------------------------------------------- 1 | // global scopes in Laravel's Eloquent ORM and provide you with some code examples. Global scopes are a convenient feature that allows you to define constraints that are automatically applied to all queries performed on a specific model. 2 | 3 | // When using global scopes, you define the constraints in a dedicated class that extends Laravel's Illuminate\Database\Eloquent\Scope class. Let's walk through an example to demonstrate how to implement global scopes in Laravel. 4 | 5 | // Step 1: Create a Global Scope Class 6 | // First, create a new PHP class that represents your global scope.This class should implement the Illuminate\Database\Eloquent\Scope interface and define a apply method.The apply method receives two arguments: the Illuminate\Database\Eloquent\Builder instance and the Illuminate\Database\Eloquent\Model instance. 7 | 8 | // Here's an example of a global scope class named ActiveScope that applies a constraint to retrieve only active records: 9 | 10 | 11 | // use Illuminate\Database\Eloquent\Builder; 12 | // use Illuminate\Database\Eloquent\Model; 13 | // use Illuminate\Database\Eloquent\Scope; 14 | 15 | // class ActiveScope implements Scope { 16 | // public function apply(Builder $builder, Model $model) { 17 | // $builder -> where('active', true); 18 | // } 19 | // } 20 | 21 | // In this example, the apply method adds a where clause to the query, restricting the results to only those where the active column is set to true. 22 | 23 | // Step 2: Register the Global Scope 24 | // Next, you need to register the global scope with your model.Open your model class (e.g., App\Models\User) and add a boot method.In this method, you can call the addGlobalScope method to register your global scope. 25 | 26 | 27 | // use App\Scopes\ActiveScope; 28 | // use Illuminate\Database\Eloquent\Model; 29 | 30 | // class User extends Model { 31 | // protected static function boot() { 32 | // parent:: boot(); 33 | 34 | // static:: addGlobalScope(new ActiveScope()); 35 | // } 36 | // } 37 | 38 | 39 | // In this example, the boot method adds the ActiveScope global scope to the User model.From now on, whenever a query is performed on the User model, the global scope's constraint will be applied. 40 | 41 | // Step 3: Usage and Testing 42 | // You can now use your model as usual, and the global scope will be automatically applied.Here's an example of retrieving all active users: 43 | 44 | 45 | // $activeUsers = User:: all(); 46 | // In this case, the global scope will add the where clause to the query, ensuring that only active users are returned. 47 | 48 | // You can also temporarily disable a global scope for a specific query by using the withoutGlobalScope method: 49 | 50 | 51 | // $inactiveUsers = User:: withoutGlobalScope(ActiveScope:: class) -> get(); 52 | // In this example, the withoutGlobalScope method allows you to bypass the ActiveScope and retrieve all users, including inactive ones. 53 | 54 | // That's it! You now understand how to implement and use global scopes in Laravel's Eloquent ORM.Remember, global scopes are powerful tools for adding constraints to all queries on a specific model, making it easier to enforce certain conditions consistently throughout your application. 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/14_local_scope.js: -------------------------------------------------------------------------------- 1 | // // local scopes in Laravel's Eloquent ORM. Local scopes allow you to define reusable query constraints on your models, making it easier to work with common query conditions. Let's dive into the concept and explore some code examples. 2 | 3 | // // To define a local scope, you need to add a method to your model class. This method should have a naming convention of scope[ScopeName], where[ScopeName] represents the name of your scope.Within the scope method, you can chain query constraints using the Eloquent query builder. 4 | 5 | // // Here's an example to illustrate the concept. Let's say we have a User model with a status column, and we want to create a local scope to retrieve only active users: 6 | 7 | 8 | // class User extends Model { 9 | // // ... 10 | 11 | // public function scopeActive($query) { 12 | // return $query -> where('status', 'active'); 13 | // } 14 | // } 15 | // In the above code, we defined a local scope named active.The scope method receives the query builder instance as its first argument(conventionally named $query).We used the where method to add a condition to the query, filtering users with the "active" status. 16 | 17 | // Now, you can use this local scope in your queries like this: 18 | 19 | 20 | // $activeUsers = User:: active() -> get(); 21 | // By calling the active scope on the User model, it applies the constraint defined in the scope, and you will receive a collection of active users. 22 | 23 | // Local scopes can also accept additional parameters if needed.For example, let's create a scope that retrieves users based on their role: 24 | 25 | 26 | // class User extends Model { 27 | // // ... 28 | 29 | // public function scopeByRole($query, $role) { 30 | // return $query -> where('role', $role); 31 | // } 32 | // } 33 | // Now you can use the byRole scope by passing the desired role as an argument: 34 | 35 | 36 | // $admins = User:: byRole('admin') -> get(); 37 | // The byRole scope allows you to easily fetch users with a specific role. 38 | 39 | // You can chain multiple local scopes together or combine them with other query builder methods.Here's an example that uses both the active and byRole scopes: 40 | 41 | 42 | // $activeAdmins = User:: active() -> byRole('admin') -> get(); 43 | // In this case, you retrieve active users with the role of "admin." 44 | 45 | // That's the basic concept of local scopes in Laravel's Eloquent ORM.They provide a convenient way to define reusable query constraints within your models, allowing you to write cleaner and more maintainable code. 46 | 47 | // I hope this explanation helps you understand local scopes in Laravel Eloquent ORM. 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/15_dynamic_scope.js: -------------------------------------------------------------------------------- 1 | // dynamic scopes in Laravel's Eloquent ORM. Dynamic scopes are a powerful feature that allows you to define reusable query constraints in your models. 2 | 3 | // To create a dynamic scope, you need to define a method in your Eloquent model.This method will return an instance of the query builder with the desired constraints.Let's dive into an example to illustrate how it works. 4 | 5 | // Let's say we have a "User" model with a "status" column that represents the status of a user. We want to define a dynamic scope to retrieve only active users. Here's how you can do it: 6 | 7 | 8 | // where('status', 'active'); 19 | // } 20 | // } 21 | // In the above code, we define a method called "scopeActive" in the "User" model.This method takes the query builder instance as a parameter and returns the modified query builder. 22 | 23 | // Now, let's see how we can use this dynamic scope: 24 | 25 | 26 | // $activeUsers = User:: active() -> get(); 27 | // In the code above, we call the "active" scope on the "User" model, which applies the "where('status', 'active')" constraint to the query.The resulting query will retrieve only the active users. 28 | 29 | // Dynamic scopes can also accept additional parameters to make them more flexible.Let's extend our example to allow filtering by a specific status: 30 | 31 | 32 | // where('status', $status); 43 | // } 44 | // } 45 | // Now we can use the "status" scope to filter users by any status we want: 46 | 47 | // $activeUsers = User:: status('active') -> get(); 48 | // $inactiveUsers = User:: status('inactive') -> get(); 49 | // By passing the status as a parameter to the "status" scope, we can retrieve users with the specified status. 50 | 51 | // Dynamic scopes can be very useful for encapsulating common query constraints and making your code more readable and maintainable.They allow you to define reusable filters that can be applied to your queries easily. 52 | 53 | // I hope this explanation and examples help you understand dynamic scopes in Laravel's Eloquent ORM. 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/16_using_trait_to_store_scope.js: -------------------------------------------------------------------------------- 1 | // Laravel Eloquent ORM and how to use traits to store scopes.Laravel provides a powerful ORM called Eloquent that allows you to interact with your database tables using an expressive and intuitive syntax.Scopes in Eloquent allow you to define reusable query constraints that can be applied to your models. 2 | 3 | // Before we dive into traits and scopes, make sure you have Laravel installed and set up.Once you're ready, let's get started! 4 | 5 | // Step 1: Creating a Trait 6 | // To store scopes in a trait, we'll start by creating a new PHP file. Let's call it ScopesTrait.php.In this file, we'll define our trait and its methods. The trait will be responsible for encapsulating our reusable scopes. 7 | 8 | 9 | // // ScopesTrait.php 10 | 11 | // namespace App\Traits; 12 | 13 | // trait ScopesTrait 14 | // { 15 | // // Define your scopes here 16 | // public function scopePublished($query) { 17 | // return $query -> where('published', true); 18 | // } 19 | 20 | // public function scopeByAuthor($query, $authorId) { 21 | // return $query -> where('author_id', $authorId); 22 | // } 23 | 24 | // // Add more scopes as needed 25 | // } 26 | // In this example, we've defined two scopes: scopePublished and scopeByAuthor. The scopePublished scope adds a constraint to filter only published records, and the scopeByAuthor scope filters records by a specific author ID. You can add more scopes based on your application's needs. 27 | 28 | // Step 2: Using the Trait in a Model 29 | // Once you have your trait defined, you can easily use it in your Eloquent models.Let's say we have a Post model. Here's an example of how to use the ScopesTrait in the Post model: 30 | 31 | 32 | // // Post.php 33 | 34 | // namespace App\Models; 35 | 36 | // use Illuminate\Database\Eloquent\Model; 37 | // use App\Traits\ScopesTrait; 38 | 39 | // class Post extends Model { 40 | // use ScopesTrait; 41 | 42 | // // Your model's properties, relationships, etc. 43 | // } 44 | // By adding use ScopesTrait in your model, you include all the methods defined in the ScopesTrait into your Post model.Now you can directly call the scopes on your Post model instance or query builder. 45 | 46 | // Step 3: Using Scopes in Queries 47 | // With the trait included in your model, you can now use the scopes in your queries.Here's an example: 48 | 49 | 50 | // $publishedPosts = Post:: published() -> get(); 51 | // In this example, we use the published scope to fetch all published posts.The published scope defined in the ScopesTrait will add the necessary constraint to the query. 52 | 53 | // You can also chain multiple scopes together: 54 | 55 | 56 | // $authorPosts = Post:: published() -> byAuthor(1) -> get(); 57 | // In this case, we first apply the published scope and then chain the byAuthor scope to filter the posts by author ID 1. 58 | 59 | // That's it! You've learned how to create a trait to store scopes and use them in Laravel Eloquent ORM.Traits provide a clean and reusable way to organize and share scopes among multiple models. 60 | 61 | // Remember, scopes are just one aspect of Laravel Eloquent ORM.There are many other powerful features and functionalities available.I encourage you to explore the Laravel documentation for more details and examples. 62 | 63 | // Happy coding! 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/4_mass_assignment.js: -------------------------------------------------------------------------------- 1 | // 👉Mass assignment in Laravel Eloquent Models and provide you with some code examples. 2 | 3 | // In Laravel, mass assignment allows you to easily assign multiple attributes to a model at once using an array.It's a convenient way to quickly set multiple properties of a model in a single line of code. However, it's important to understand how to properly use mass assignment to ensure security and avoid potential vulnerabilities. 4 | 5 | // To enable mass assignment on a model, you need to specify the fillable or guarded properties.The fillable property is an array that contains a list of attributes that are allowed to be mass assigned, while the guarded property contains attributes that are not allowed to be mass assigned. 6 | 7 | // Here's an example of how to use mass assignment in Laravel Eloquent Models: 8 | 9 | // Define the fillable attributes in your model: 10 | 11 | // namespace App\Models; 12 | 13 | // use Illuminate\Database\Eloquent\Model; 14 | 15 | // class User extends Model { 16 | // protected $fillable = [ 17 | // 'name', 'email', 'password', 18 | // ]; 19 | 20 | // // ... 21 | // } 22 | // In the example above, the name, email, and password attributes are fillable, meaning they can be assigned using mass assignment. 23 | 24 | // Now, you can create a new instance of the model and set multiple attributes using mass assignment: 25 | 26 | // $user = User:: create([ 27 | // 'name' => 'John Doe', 28 | // 'email' => 'johndoe@example.com', 29 | // 'password' => bcrypt('password123'), 30 | // ]); 31 | // In the code above, we're using the create method, which accepts an array of attributes to be assigned to the model. This will create a new user instance and assign the values specified in the array. 32 | 33 | // It's worth noting that the create method will automatically save the model to the database. If you want to perform additional operations on the model before saving, you can use the fill method instead: 34 | 35 | 36 | // $user = new User(); 37 | // $user -> fill([ 38 | // 'name' => 'John Doe', 39 | // 'email' => 'johndoe@example.com', 40 | // 'password' => bcrypt('password123'), 41 | // ]); 42 | // $user -> save(); 43 | // By using the fill method, you can set the attributes without saving the model immediately. 44 | 45 | // It's important to keep security in mind when using mass assignment. To protect against unwanted mass assignment, you can use the guarded property instead of fillable. Attributes listed in the guarded property will be excluded from mass assignment. 46 | 47 | 48 | // namespace App\Models; 49 | 50 | // use Illuminate\Database\Eloquent\Model; 51 | 52 | // class User extends Model { 53 | // protected $guarded = ['admin']; 54 | 55 | // // ... 56 | // } 57 | // In the example above, the admin attribute is guarded, meaning it cannot be mass assigned.This can be useful for sensitive attributes that should only be assigned through specific methods. 58 | 59 | // That's a brief explanation of mass assignment in Laravel Eloquent Models. Remember to properly configure the fillable and guarded properties to ensure the security of your application. 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/5_route_model_binding.js: -------------------------------------------------------------------------------- 1 | // 👉Route model binding in Laravel.Route model binding is a convenient feature in Laravel that allows you to automatically inject model instances into your route closures or controller methods based on the route parameters.It helps simplify your code by eliminating the need to manually fetch the model instance. 2 | 3 | // Let's dive into the details and see how route model binding works. 4 | 5 | // Step 1: Define a Route 6 | // First, let's define a route that includes a parameter representing the model identifier. For example, suppose we have a Post model, and we want to retrieve a specific post based on its ID: 7 | 8 | 9 | // Route:: get('/posts/{post}', 'PostController@show'); 10 | 11 | // Step 2: Enable Route Model Binding 12 | // To enable route model binding, you need to update your route definition or use a route binding helper.In this case, we'll use the implicit binding feature, which automatically resolves the model instance by looking for the appropriate attribute (in this case, the id column) in the database. 13 | 14 | // Open the RouteServiceProvider class located in the app / Providers directory.In the boot method, add the following code: 15 | 16 | 17 | // use App\Models\Post; 18 | 19 | // public function boot() { 20 | // parent:: boot(); 21 | 22 | // Route:: model('post', Post:: class); 23 | // } 24 | // Alternatively, you can use the Route::bind method to customize the binding behavior.However, for most cases, the Route::model method is sufficient. 25 | 26 | // Step 3: Implement the Controller Method 27 | // Next, let's implement the corresponding show method in the PostController. Laravel will automatically resolve the Post instance and inject it as an argument. 28 | 29 | 30 | // use App\Models\Post; 31 | 32 | // public function show(Post $post) { 33 | // return view('posts.show', compact('post')); 34 | // } 35 | // Here, the $post parameter will contain the instance of the Post model that matches the provided ID from the route. 36 | 37 | // Step 4: Use the Model Instance 38 | // Now that you have the Post model instance available, you can use it within your method as needed.In this example, we're passing the $post instance to a view. 39 | 40 | // Step 5: Route Model Binding with Custom Column 41 | // If your model uses a column other than id for route model binding, you can specify the column name in the getRouteKeyName method of your model.For example, if your Post model uses a slug column: 42 | 43 | 44 | // public function getRouteKeyName() { 45 | // return 'slug'; 46 | // } 47 | // This will tell Laravel to resolve the model instance using the slug column instead of id. 48 | 49 | // That's it! You've learned how to use route model binding in Laravel.Now, when you visit a URL like / posts / 1, Laravel will automatically fetch the corresponding Post instance and inject it into your route or controller method. 50 | 51 | // Keep in mind that route model binding also works with other HTTP verbs like POST, PUT, and DELETE.You can apply the same principles to those routes as well. 52 | 53 | // I hope this explanation and code examples help you understand route model binding in Laravel.If you have any further questions, feel free to ask! 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/6_firstOrCreate_vs_firstOrNew_method.js: -------------------------------------------------------------------------------- 1 | // In Laravel's Eloquent ORM, both the firstOrCreate() and firstOrNew() methods are used for finding or creating a model instance in the database. However, they differ in their behavior and purpose. Let's explore each method: 2 | 3 | // firstOrCreate(): 4 | // The firstOrCreate() method attempts to find the first record that matches the given attributes.If a record is found, it is returned.If no matching record is found, a new record is created with the provided attributes and then returned.The method's signature is as follows: 5 | 6 | // Model:: firstOrCreate(array $attributes, array $values = []) 7 | 8 | // Here, $attributes represents the attributes to search for, and $values represents the additional attributes to set when creating a new record. 9 | 10 | // Example usage: 11 | 12 | 13 | // $user = User:: firstOrCreate(['email' => 'john@example.com'], ['name' => 'John Doe']); 14 | 15 | // In this example, the firstOrCreate() method will search for a user with the email address 'john@example.com'.If found, it returns the existing user.If not found, it creates a new user with the given email and name, and then returns it. 16 | 17 | // firstOrNew(): 18 | // The firstOrNew() method also attempts to find the first record that matches the given attributes.If a record is found, it is returned.However, if no matching record is found, a new instance of the model is created with the provided attributes, but it is not saved to the database.The method's signature is as follows: 19 | 20 | // Model:: firstOrNew(array $attributes, array $values = []) 21 | // Similar to firstOrCreate(), $attributes represents the attributes to search for, and $values represents the additional attributes to set when creating a new instance. 22 | 23 | // Example usage: 24 | 25 | 26 | // $user = User:: firstOrNew(['email' => 'john@example.com'], ['name' => 'John Doe']); 27 | 28 | // In this example, the firstOrNew() method will search for a user with the email address 'john@example.com'.If found, it returns the existing user.If not found, it creates a new instance of the User model with the given email and name, but the instance is not saved to the database. 29 | 30 | // To save the instance returned by firstOrNew(), you need to call the save() method explicitly. 31 | 32 | 33 | // $user -> save(); 34 | 35 | // This will persist the newly created user to the database. 36 | 37 | // In summary, firstOrCreate() finds the first record matching the provided attributes, and if none is found, it creates and saves a new record to the database.On the other hand, firstOrNew() finds the first record matching the attributes, and if none is found, it creates a new instance of the model without saving it to the database. 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/7_Attribute_Changes_isDirty_isClean_wasChanged.js: -------------------------------------------------------------------------------- 1 | // In Laravel's Eloquent ORM, there are several attribute-related methods that you can use to track changes and determine the state of an attribute. These methods include isDirty(), isClean(), and wasChanged(). Let's explore each of these methods in detail: 2 | 3 | // isDirty(): This method allows you to check if an attribute has been modified since the model was loaded or saved.In other words, it determines if the attribute value differs from its original value.The isDirty() method returns a boolean value of true if the attribute has been modified, and false otherwise. 4 | 5 | // Here's an example usage of isDirty(): 6 | 7 | 8 | // $user = User:: find(1); 9 | // $user -> name = 'John Doe'; 10 | 11 | // if ($user -> isDirty('name')) { 12 | // // The 'name' attribute has been modified 13 | // echo "Name has changed!"; 14 | // } else { 15 | // // The 'name' attribute remains the same 16 | // echo "Name has not changed."; 17 | // } 18 | 19 | // In the example above, if the 'name' attribute of the $user model has been modified, it will echo "Name has changed!". 20 | 21 | // isClean(): The isClean() method is the inverse of isDirty().It checks if there have been no changes to the specified attribute.If the attribute is clean, meaning it has not been modified, isClean() returns true; otherwise, it returns false. 22 | 23 | // Here's an example usage of isClean(): 24 | 25 | 26 | // $user = User:: find(1); 27 | 28 | // if ($user -> isClean('name')) { 29 | // // The 'name' attribute has not been modified 30 | // echo "Name has not changed."; 31 | // } else { 32 | // // The 'name' attribute has been modified 33 | // echo "Name has changed!"; 34 | // } 35 | 36 | // In the example above, if the 'name' attribute of the $user model has not been modified, it will echo "Name has not changed.". 37 | 38 | // wasChanged(): The wasChanged() method checks if an attribute was changed during the current request, regardless of whether it was saved or not.It returns true if the attribute was modified, and false if it remained the same. 39 | 40 | // Here's an example usage of wasChanged(): 41 | 42 | 43 | // $user = User:: find(1); 44 | // $user -> name = 'John Doe'; 45 | 46 | // if ($user -> wasChanged('name')) { 47 | // // The 'name' attribute was changed during the current request 48 | // echo "Name has changed!"; 49 | // } else { 50 | // // The 'name' attribute remained the same during the current request 51 | // echo "Name has not changed."; 52 | // } 53 | 54 | 55 | // In the example above, if the 'name' attribute of the $user model was changed during the current request, it will echo "Name has changed!". 56 | 57 | // These methods are useful when you need to determine if specific attributes have been modified in your Laravel application.You can use them to perform certain actions or validations based on attribute changes. 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/8_updateOrCreate_upsert.js: -------------------------------------------------------------------------------- 1 | // 👉 updateOrCreate() and upsert() methods in Laravel's Eloquent ORM : 2 | 3 | // These methods are used for updating or inserting records in the database table, and they can be quite handy in certain situations.I'll explain each method separately and provide code examples to demonstrate their usage. 4 | 5 | // ✅ updateOrCreate() Method: 6 | // The updateOrCreate() method allows you to update an existing record in the database or create a new record if it doesn't already exist. It takes two parameters: an array of attributes to update or create, and an array of values to set on the record. Here's an example: 7 | 8 | // Suppose we have a "users" table with columns: id, name, email, and phone_number 9 | 10 | // Updating an existing record if it exists, or creating a new one 11 | // $user = User:: updateOrCreate( 12 | // ['email' => 'john@example.com'], // Search criteria to find the record 13 | // ['name' => 'John Doe', 'phone_number' => '123456789'] // Attributes to update or set 14 | // ); 15 | 16 | // In this example, if a user with the email 'john@example.com' exists, their name and phone number will be updated. 17 | // Otherwise, a new user will be created with the provided attributes. 18 | 19 | // In the above code, we use the User model(assuming you have a User model class) to perform the updateOrCreate() operation.The first array specifies the search criteria to find the record(in this case, we search for a user with the email 'john@example.com'). The second array contains the attributes to update or set on the record. 20 | 21 | // ✅ upsert() Method: 22 | // The upsert() method is similar to updateOrCreate(), but it allows you to perform an "upsert" operation, which means updating an existing record or inserting a new record based on a specified unique key.Here's an example: 23 | 24 | // Suppose we have a "products" table with columns: id, name, price, and in_stock 25 | 26 | // Upserting a product based on the unique key "name" 27 | // Product:: upsert( 28 | // [ 29 | // ['name' => 'iPhone', 'price' => 999.99, 'in_stock' => 10], 30 | // ['name' => 'MacBook', 'price' => 1999.99, 'in_stock' => 5] 31 | // ], 32 | // ['name'], // Unique key(s) to identify existing records 33 | // ['price', 'in_stock'] // Attributes to update if the record already exists 34 | // ); 35 | 36 | // In this example, we provide an array of products to upsert. 37 | // The 'name' column is considered the unique key. 38 | // If a product with the same name already exists, its 'price' and 'in_stock' attributes will be updated. 39 | // Otherwise, new products will be inserted with the provided attributes. 40 | 41 | // In the upsert() method, the first parameter is an array of records to upsert.Each record is represented by an associative array with the column names as keys and the corresponding values.The second parameter specifies the unique key(s) used to identify existing records(in this case, the 'name' column).The third parameter contains the attributes to update if the record already exists. 42 | 43 | // These methods are quite useful when you want to update or insert records in a database table efficiently and in a concise manner.Make sure to adjust the examples to match your specific database table structure and model names. 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/9_delete_truncate_destroy.js: -------------------------------------------------------------------------------- 1 | // 👉delete (), truncate(), and destroy() methods in Laravel's Eloquent ORM. 2 | 3 | // These methods are used for manipulating data in the database using the models in Laravel. 4 | 5 | // ✅delete (): This method is used to delete a specific record from the database.It can be called on an instance of a model or a collection of models. 6 | 7 | // ✅Deleting a single record 8 | // $user = User:: find(1); 9 | // $user -> delete (); 10 | 11 | // ✅Deleting multiple records 12 | // User:: where('status', 'inactive') -> delete (); 13 | 14 | // In the first example, we retrieve a user with an ID of 1 and delete it using the delete () method.In the second example, we delete all users with an "inactive" status. 15 | 16 | //✅ truncate(): This method is used to remove all records from a table.It can be called on a model's class. 17 | 18 | // User:: truncate(); 19 | 20 | // The truncate() method removes all records from the users table in the above example. 21 | 22 | // ✅destroy(): This method is used to delete one or more records by their primary keys.It can be called on a model's class or a collection of models. 23 | 24 | // Deleting a single record 25 | // User:: destroy(1); 26 | 27 | // Deleting multiple records 28 | // User:: destroy([1, 2, 3]); 29 | 30 | // Deleting records based on a condition 31 | // User:: where('status', 'inactive') -> delete (); 32 | 33 | // In the first example, we delete a user with the primary key 1 using the destroy() method.In the second example, we delete multiple users with primary keys 1, 2, and 3. Lastly, we delete all users with an "inactive" status using a condition. 34 | 35 | // It's important to note that the delete() and destroy() methods trigger the model's events and perform cascading deletes if defined in the relationships.On the other hand, the truncate() method does not trigger events and does not fire any cascading deletes. 36 | 37 | // Remember to import the relevant model at the top of your file using the use statement.For example: use App\Models\User;. 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm/eloquent_orm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/eloquent_orm/eloquent_orm.png -------------------------------------------------------------------------------- /understanding_laravel/eloquent_orm_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/eloquent_orm_2.png -------------------------------------------------------------------------------- /understanding_laravel/hydration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/hydration.png -------------------------------------------------------------------------------- /understanding_laravel/model_migration_seeder_factory/apiResourceRoute.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, the apiResource route is a convenient way to define multiple routes for a resourceful API controller. It provides a consistent naming convention and automatically maps the routes to the corresponding controller methods. 3 | 4 | To use apiResource, you'll need to define a route in your routes/api.php file. Here's an example: 5 | 6 | 7 | use App\Http\Controllers\API\PostController; 8 | 9 | Route::apiResource('posts', PostController::class); 10 | In this example, we're defining a resource route for the posts endpoint and associating it with the PostController class. 11 | 12 | This single line of code automatically generates the following routes: 13 | 14 | 15 | GET /posts - index() - Retrieves all posts 16 | POST /posts - store() - Creates a new post 17 | GET /posts/{id} - show() - Retrieves a specific post 18 | PUT/PATCH /posts/{id} - update() - Updates a specific post 19 | DELETE /posts/{id} - destroy() - Deletes a specific post 20 | Now, let's dive into each method and its purpose: 21 | 22 | index(): This method handles the GET request to retrieve all posts. You can define the logic to fetch and return all posts from your database. 23 | 24 | store(): This method handles the POST request to create a new post. You can define the logic to validate and store the new post in your database. 25 | 26 | show($id): This method handles the GET request to retrieve a specific post based on its ID. You can define the logic to fetch and return the post with the given ID. 27 | 28 | update($id): This method handles the PUT/PATCH request to update a specific post. You can define the logic to validate and update the post with the given ID in your database. 29 | 30 | destroy($id): This method handles the DELETE request to delete a specific post. You can define the logic to delete the post with the given ID from your database. 31 | 32 | By using apiResource, you save time by not having to manually define each route separately. Laravel automatically maps the HTTP methods to the appropriate controller methods based on the naming convention. 33 | 34 | Remember to replace PostController with the actual name of your API controller class, and customize the logic within each controller method to fit your application's needs. 35 | 36 | I hope this explanation helps you understand the concept of apiResource in Laravel! 37 | */ -------------------------------------------------------------------------------- /understanding_laravel/model_migration_seeder_factory/factory.js: -------------------------------------------------------------------------------- 1 | /* 2 | Factories are used for generating dummy data or test data in Laravel applications. They provide a convenient way to create model instances with predefined attributes. 3 | 4 | To begin, let's assume you have a model called User and you want to create a factory to generate fake user data. Here's how you can do it: 5 | 6 | Create a Factory: 7 | In Laravel, factories are typically stored in the database/factories directory. Start by creating a new file called UserFactory.php in that directory. 8 | 9 | Define the Factory: 10 | Open UserFactory.php and import the necessary classes at the top of the file. Then, use the define method to define the attributes for the User model. 11 | 12 | 13 | use App\Models\User; 14 | use Faker\Generator as Faker; 15 | 16 | $factory->define(User::class, function (Faker $faker) { 17 | return [ 18 | 'name' => $faker->name, 19 | 'email' => $faker->unique()->safeEmail, 20 | 'password' => bcrypt('password'), // Example: setting a fixed password 21 | ]; 22 | }); 23 | In this example, the factory is defining attributes like the user's name, email, and a fixed password for simplicity. The Faker class is used to generate random data for the attributes. 24 | 25 | Generate Dummy Data: 26 | To generate dummy data using the factory, you can use the factory helper function in your code or in database seeders. Here's an example of how you can use it in a seeder: 27 | 28 | use Illuminate\Database\Seeder; 29 | use App\Models\User; 30 | 31 | class UserSeeder extends Seeder 32 | { 33 | public function run() 34 | { 35 | factory(User::class, 10)->create(); 36 | } 37 | } 38 | In this example, we're using the factory function to create ten instances of the User model. The create method will persist these instances to the database. 39 | 40 | Running the Seeder: 41 | To run the seeder and populate the database with dummy users, you can use the db:seed Artisan command in Laravel's command-line interface: 42 | 43 | php artisan db:seed --class=UserSeeder 44 | That's it! Now you have a basic understanding of how to use factories in Laravel to generate dummy data. Feel free to customize the attributes in the factory definition to suit your needs. 45 | 46 | Remember, factories are particularly useful for testing and database seeding, as they allow you to create consistent, realistic data for your application. 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | */ -------------------------------------------------------------------------------- /understanding_laravel/model_migration_seeder_factory/migration.js: -------------------------------------------------------------------------------- 1 | /* 2 | Migrations in Laravel are a way to manage your database schema and version control it over time. They allow you to define and modify database tables and their columns in a structured and organized manner. With migrations, you can easily create, update, and rollback database schema changes as your application evolves. 3 | 4 | Migrations are created using Laravel's Artisan command-line tool. To create a migration, you can use the following command: 5 | 6 | 7 | php artisan make:migration create_users_table 8 | This command will generate a new migration file with a timestamp and the given name, such as 20220516123700_create_users_table.php. The migration files are stored in the database/migrations directory. 9 | 10 | Inside the migration file, you will find two main methods: up() and down(). The up() method is responsible for defining the actions that should be performed when running the migration, such as creating or modifying database tables. The down() method defines the actions to be performed when rolling back or reverting the migration. 11 | 12 | Here's an example of a migration file that creates a users table: 13 | 14 | 15 | 16 | 17 | use Illuminate\Database\Migrations\Migration; 18 | use Illuminate\Database\Schema\Blueprint; 19 | use Illuminate\Support\Facades\Schema; 20 | 21 | class CreateUsersTable extends Migration 22 | { 23 | /** 24 | * Run the migration. 25 | * 26 | * @return void 27 | */ 28 | // public function up() { 29 | // Schema:: create('users', function (Blueprint $table) { 30 | // $table -> id(); 31 | // $table -> string('name'); 32 | // $table -> string('email') -> unique(); 33 | // $table -> string('password'); 34 | // $table -> timestamps(); 35 | // }); 36 | // } 37 | 38 | /** 39 | * Reverse the migration. 40 | * 41 | // * @return void 42 | */ 43 | // public function down() { 44 | // Schema:: dropIfExists('users'); 45 | // } 46 | // } 47 | // In this example: 48 | 49 | // The up() method uses the Schema facade to define the table structure using the create() method.Inside the create() method, we pass a closure that receives a Blueprint instance, allowing us to define the table's columns. In this case, we create columns for id, name, email, password, and timestamps. 50 | 51 | // The down() method uses the dropIfExists() method to drop the users table if the migration needs to be rolled back. 52 | 53 | // To run the migrations and create the database tables, you can use the following Artisan command: 54 | 55 | 56 | // php artisan migrate 57 | // This command will execute any pending migrations that haven't been run yet. Laravel keeps track of which migrations have been executed in a table named migrations in your database. 58 | 59 | // You can also rollback or undo migrations using the following command: 60 | 61 | 62 | // php artisan migrate: rollback 63 | // This command will revert the last batch of migrations, effectively undoing the changes made by the most recent migration. 64 | 65 | // Migrations provide a structured and efficient way to manage your database schema.They make it easy to version control your database changes and ensure consistency across different environments.By using migrations, you can evolve your database schema over time without having to manually modify the tables. 66 | 67 | // I hope this explanation helps you understand the concept of migrations in Laravel.If you have any further questions, feel free to ask! 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /understanding_laravel/model_migration_seeder_factory/model.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, a model represents a specific table in your database and provides an abstraction layer for interacting with that table's records. Models allow you to perform common database operations such as retrieving, creating, updating, and deleting records, as well as defining relationships between different tables. 3 | 4 | To create a model in Laravel, you can use the Artisan command php artisan make:model. For example, let's say you have a table named users in your database. You can create a corresponding model named User by running the following command: 5 | 6 | 7 | php artisan make:model User 8 | This command will generate a new User model file under the app directory. 9 | 10 | Once you have created a model, you can define its properties and methods to interact with the associated database table. 11 | 12 | Here's an example of a User model with some common features: 13 | 14 | 15 | hasMany(Post::class); 31 | } 32 | 33 | // Define custom methods to perform operations on the User model 34 | public function getFullName() 35 | { 36 | return $this->first_name . ' ' . $this->last_name; 37 | } 38 | } 39 | Let's break down the important parts of this example: 40 | 41 | The User model extends the base Model class provided by Laravel. This gives you access to various methods and features for interacting with the database. 42 | 43 | The protected $table property specifies the name of the database table associated with the model. In this case, it is set to 'users'. 44 | 45 | The protected $fillable property defines an array of fields that are mass assignable. These fields can be set using the create() or update() methods. In this example, we allow the 'name', 'email', and 'password' fields to be mass assignable. 46 | 47 | The public function posts() method defines a relationship between the User model and another model called Post. In this case, it represents a one-to-many relationship where a user can have multiple posts. This method uses the hasMany() method provided by Laravel's Eloquent ORM. 48 | 49 | The public function getFullName() method is a custom method defined on the User model. It can be used to perform operations specific to the user model, such as retrieving the full name of a user. 50 | 51 | With the User model defined, you can now perform various operations on the associated users table. Here are some examples: 52 | 53 | 54 | // Retrieve all users 55 | $users = User::all(); 56 | 57 | // Create a new user 58 | $user = User::create([ 59 | 'name' => 'John Doe', 60 | 'email' => 'john@example.com', 61 | 'password' => bcrypt('password123'), 62 | ]); 63 | 64 | // Update a user's name 65 | $user = User::find(1); 66 | $user->name = 'New Name'; 67 | $user->save(); 68 | 69 | // Delete a user 70 | $user = User::find(1); 71 | $user->delete(); 72 | In the examples above, we use static methods such as all(), create(), and find() provided by the User model to perform common database operations. Additionally, we can access relationships and custom methods defined on the model, such as $user->posts() or $user->getFullName(). 73 | 74 | Models in Laravel provide a powerful and convenient way to interact with your database tables. 75 | */ -------------------------------------------------------------------------------- /understanding_laravel/model_migration_seeder_factory/seeder.js: -------------------------------------------------------------------------------- 1 | /* 2 | Seeders are used for populating the database with initial or dummy data. They allow you to insert records into database tables automatically. 3 | 4 | Here's a step-by-step guide on using seeders in Laravel: 5 | 6 | Create a Seeder: 7 | In Laravel, seeders are typically stored in the database/seeders directory. To create a new seeder, use the make:seeder Artisan command: 8 | 9 | php artisan make:seeder UsersTableSeeder 10 | This command will generate a new seeder file named UsersTableSeeder.php. 11 | 12 | Define the Seeder: 13 | Open UsersTableSeeder.php and import the necessary classes at the top of the file. Then, within the run method, use the Eloquent ORM to insert records into the users table. 14 | 15 | use Illuminate\Database\Seeder; 16 | use App\Models\User; 17 | 18 | class UsersTableSeeder extends Seeder 19 | { 20 | public function run() 21 | { 22 | User::create([ 23 | 'name' => 'John Doe', 24 | 'email' => 'johndoe@example.com', 25 | 'password' => bcrypt('password'), 26 | ]); 27 | 28 | User::create([ 29 | 'name' => 'Jane Smith', 30 | 'email' => 'janesmith@example.com', 31 | 'password' => bcrypt('password'), 32 | ]); 33 | 34 | // You can create more users or insert other records as needed 35 | } 36 | } 37 | In this example, we're using the create method of the User model to insert two user records into the users table. You can add more records or insert data into other tables based on your application's requirements. 38 | 39 | Run the Seeder: 40 | To execute the seeder and populate the database with the defined records, you can use the db:seed Artisan command: 41 | 42 | php artisan db:seed --class=UsersTableSeeder 43 | Running this command will invoke the run method within the UsersTableSeeder class and insert the defined records into the database. 44 | 45 | Note: By default, the DatabaseSeeder.php file, located in the database/seeders directory, is used as the entry point for running all the seeders. It can be used to call multiple seeders at once. 46 | 47 | Running Multiple Seeders: 48 | To run multiple seeders, you can define the seeder classes to be executed within the DatabaseSeeder.php file. For example: 49 | 50 | use Illuminate\Database\Seeder; 51 | 52 | class DatabaseSeeder extends Seeder 53 | { 54 | public function run() 55 | { 56 | $this->call([ 57 | UsersTableSeeder::class, 58 | ProductsTableSeeder::class, 59 | // Add more seeders here if needed 60 | ]); 61 | } 62 | } 63 | In this example, we're calling the UsersTableSeeder and ProductsTableSeeder to populate both the users and products tables. 64 | 65 | Running All Seeders: 66 | To run all seeders at once, you can simply use the db:seed Artisan command without specifying a specific seeder class: 67 | 68 | php artisan db:seed 69 | Running this command will execute the run method of all seeders defined within the DatabaseSeeder.php file. 70 | 71 | That's it! Now you have a basic understanding of how to use seeders in Laravel to populate the database with initial or dummy data. Seeders are particularly useful for setting up sample data for testing or creating default records for your application. 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | */ -------------------------------------------------------------------------------- /understanding_laravel/note.js: -------------------------------------------------------------------------------- 1 | /* 2 | Php artisan Commands: 3 | 1. php artisan 4 | 2. php artisan about 5 | 3. php artisan make:model Post -a or php artisan model -all 6 | 4. php artisan inspire 7 | 5. php artisan route:list 8 | 9 | 10 | */ 11 | 12 | /* 13 | Basic Terms : 14 | 1.Folder Structure 15 | 2.Artisan commands overview 16 | 3..env file 17 | 4. Routing 18 | a. Overview and defining routes 19 | b. Managing and named routes 20 | c. Required Route Parameters and optional route parameters 21 | d. Constraining possible Route parameters values 22 | 5. Blade Template Engine and Views 23 | a.Understanding blade template engine, views and templating 24 | b. Blade inheritance and template layout 25 | c. Passing and rendering data in templates 26 | d. Conditional rendering 27 | e. Partial Templating and loop in partial templating 28 | 6. Request and response Lifecycle 29 | a. Understanding request and response lifecycle 30 | b. Headers and cookies in response code 31 | c. Redirect response 32 | d. Returning Json Response 33 | e. Returning File Download 34 | f. Grouping Routes 35 | g. Request input 36 | 7. Middleware: Running code before and after request 37 | 38 | 39 | 40 | 41 | */ 42 | 43 | 44 | /* 45 | Extensions : 46 | 3. VS Code Extensions: 47 | PHP Extensions 48 | a. PHP Extension Pack 49 | b .PHP IntelliSense 50 | c. PHP Namespace Resolver 51 | d. phpfmt - PHP formatter 52 | e. Php Intelephense 53 | Laravel Extensions 54 | a. Laravel Extension Pack 55 | b. Laravel Blade Formatter 56 | c. Laravel Blade Snippets 57 | d. Laravel Extra Intellisense 58 | e. Laravel Artisan 59 | Helpful Optional 60 | a. Auto Close, Auto Complete, Rename Tag 61 | b. Prettier 62 | c. Rainbow Brackets 63 | d. Color Highlight 64 | e. dotEnv 65 | 66 | 67 | */ -------------------------------------------------------------------------------- /understanding_laravel/observer_design_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/observer_design_pattern.png -------------------------------------------------------------------------------- /understanding_laravel/php_premier/HasFactory_trait.js: -------------------------------------------------------------------------------- 1 | /* 2 | The HasFactory trait is a convenient feature provided by Laravel for generating model factories. It allows you to define a factory for a model using a simple and expressive syntax, making it easier to generate dummy data for testing and seeding databases. 3 | 4 | Here's an example to demonstrate the concept of the HasFactory trait: 5 | 6 | 7 | use Illuminate\Database\Eloquent\Factories\HasFactory; 8 | use Illuminate\Database\Eloquent\Model; 9 | 10 | class Post extends Model 11 | { 12 | use HasFactory; 13 | 14 | // Rest of the class implementation 15 | } 16 | In this example, we have a Post model class that extends the Model class provided by Laravel's Eloquent ORM. By including the HasFactory trait in the Post class using the use keyword, we enable the factory generation functionality for that model. 17 | 18 | To generate a factory for the Post model, you need to create a corresponding factory class. Laravel provides an artisan command php artisan make:factory to generate a factory class based on the model: 19 | 20 | 21 | php artisan make:factory PostFactory --model=Post 22 | Running the above command will generate a PostFactory class in the database/factories directory. The generated factory class will already have some boilerplate code, including a definition for the Post model: 23 | 24 | 25 | use App\Models\Post; 26 | use Illuminate\Database\Eloquent\Factories\Factory; 27 | 28 | class PostFactory extends Factory 29 | { 30 | protected $model = Post::class; 31 | 32 | // Rest of the factory implementation 33 | } 34 | Now, you can define the attributes and data generation logic within the PostFactory class to create fake data for the Post model. For example: 35 | 36 | 37 | use App\Models\Post; 38 | use Illuminate\Database\Eloquent\Factories\Factory; 39 | 40 | class PostFactory extends Factory 41 | { 42 | protected $model = Post::class; 43 | 44 | public function definition() 45 | { 46 | return [ 47 | 'title' => $this->faker->sentence, 48 | 'body' => $this->faker->paragraph, 49 | ]; 50 | } 51 | } 52 | In the definition() method, you can define the attributes and their corresponding fake data using the faker property provided by Laravel's Faker library. In this case, we generate a random title and body for the Post model. 53 | 54 | With the factory defined, you can now use it to generate fake instances of the Post model in your tests or database seeding: 55 | 56 | 57 | $posts = Post::factory()->count(10)->create(); 58 | In the above example, we use the Post model's factory to generate 10 fake instances of Post and persist them to the database using the create() method. 59 | 60 | Using the HasFactory trait and generating model factories with the PostFactory class simplifies the process of generating dummy data for testing and seeding databases. It provides a clean and expressive way to define the attributes and their fake data, making it easier to create test data with varying values. 61 | 62 | I hope this explanation helps you understand the HasFactory trait and its usage for generating model factories in Laravel! 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | */ -------------------------------------------------------------------------------- /understanding_laravel/php_premier/trait.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, a trait is a way to reuse and share code across multiple classes. Traits provide a mechanism for horizontal code reuse, allowing you to define reusable code snippets that can be included in multiple classes without the need for inheritance. 3 | 4 | Traits are particularly useful when you have common functionality or methods that you want to include in multiple classes, but don't want to create a parent class hierarchy. With traits, you can easily group and reuse code snippets across different classes, promoting code reusability and maintainability. 5 | 6 | Here's an example to demonstrate the concept of traits in Laravel: 7 | 8 | 9 | trait Auditable { 10 | public function createdBy() { 11 | // Implementation goes here 12 | } 13 | 14 | public function updatedBy() { 15 | // Implementation goes here 16 | } 17 | } 18 | 19 | class Post { 20 | use Auditable; 21 | 22 | // Rest of the class implementation 23 | } 24 | 25 | class User { 26 | use Auditable; 27 | 28 | // Rest of the class implementation 29 | } 30 | In this example, we have a trait called Auditable that defines two methods: createdBy() and updatedBy(). These methods represent common functionality related to tracking the creator and updater of an entity. 31 | 32 | The Auditable trait can be included in multiple classes, such as Post and User, by using the use keyword. By including the trait, the methods defined in the trait become available in those classes. 33 | 34 | For instance, both the Post and User classes will now have access to the createdBy() and updatedBy() methods, allowing them to implement the desired behavior for tracking the creators and updaters. 35 | 36 | Using traits provides a clean and modular way to share functionality across classes without the constraints of class inheritance. It allows you to group related code snippets together and reuse them as needed throughout your application. 37 | 38 | It's worth noting that Laravel provides several built-in traits, such as HasFactory, SoftDeletes, and Notifiable, which offer commonly used functionality and can be included in your models for added features and convenience. 39 | 40 | Overall, traits in Laravel are a powerful tool for code reuse and modular development, helping you write cleaner, more maintainable code by encapsulating and sharing common functionality across multiple classes. 41 | */ 42 | 43 | 44 | /* 45 | In Laravel, the traits provided by the framework are located in the Illuminate\Support\Traits namespace. These traits are part of the Laravel framework and are typically used to extend the functionality of various classes within the framework. 46 | 47 | Here are a few commonly used traits and their corresponding namespaces: 48 | 49 | Illuminate\Foundation\Auth\Access\AuthorizesRequests: This trait provides authorization methods for controllers and is used to handle user authorization in routes and controllers. 50 | 51 | Illuminate\Foundation\Auth\RegistersUsers: This trait provides registration functionality for user authentication and is used by the RegisterController in Laravel's default authentication setup. 52 | 53 | Illuminate\Database\Eloquent\SoftDeletes: This trait enables soft deleting of models, allowing you to mark records as deleted without actually removing them from the database. 54 | 55 | Illuminate\Notifications\Notifiable: This trait adds notification support to a class, allowing it to send various types of notifications via email, SMS, Slack, etc. 56 | 57 | Illuminate\Foundation\Auth\ResetsPasswords: This trait provides password reset functionality for user authentication and is used by the ResetPasswordController in Laravel's default authentication setup. 58 | 59 | Illuminate\Auth\Authenticatable: This trait provides authentication methods and properties for user models, allowing them to authenticate users using Laravel's authentication system. 60 | 61 | These are just a few examples of the traits provided by Laravel. There are many more traits available in different namespaces within the framework, catering to various functionalities and features. 62 | 63 | It's worth noting that you can also create your own traits in Laravel by defining them within your application's namespace. By creating custom traits, you can encapsulate and reuse specific pieces of code across multiple classes in your application, promoting code reusability and maintainability. 64 | 65 | Overall, traits in Laravel can be found in various namespaces within the framework, and they serve as a way to extend and reuse functionality across different classes in a modular and organized manner. 66 | */ -------------------------------------------------------------------------------- /understanding_laravel/php_premier/understanding_guard.js: -------------------------------------------------------------------------------- 1 | /* 2 | Guards in Laravel provide a way to authenticate users and protect different parts of your application based on their authentication status. Laravel ships with several guard implementations out of the box, such as the session guard, token guard, and more. Here's a step-by-step explanation of how Guards work in Laravel: 3 | 4 | Guard Configuration: 5 | The guard configuration in Laravel is defined in the config/auth.php file. This file contains an array of guards and their corresponding configurations. Each guard specifies the driver it uses, the provider it relies on, and other settings. 6 | 7 | 8 | 'guards' => [ 9 | 'web' => [ 10 | 'driver' => 'session', 11 | 'provider' => 'users', 12 | ], 13 | 'api' => [ 14 | 'driver' => 'token', 15 | 'provider' => 'users', 16 | ], 17 | ], 18 | In the example above, two guards are defined: the 'web' guard and the 'api' guard. The 'web' guard uses the session driver and the 'users' provider, while the 'api' guard uses the token driver and the 'users' provider. 19 | 20 | Authentication Process: 21 | The authentication process in Laravel involves the following steps: 22 | 23 | Retrieving a specific guard instance using the Auth facade or by specifying the guard's name. 24 | Authenticating a user by calling the attempt method on the guard instance with the appropriate credentials. 25 | Storing the authenticated user in the session or generating a token for stateless authentication. 26 | 27 | use Illuminate\Support\Facades\Auth; 28 | 29 | if (Auth::guard('web')->attempt(['email' => $email, 'password' => $password])) { 30 | // User is authenticated 31 | } 32 | In the code snippet above, the Auth facade is used to retrieve the 'web' guard instance. The attempt method is then called on the guard instance, passing the user's email and password for authentication. 33 | 34 | Authentication Middleware: 35 | Laravel provides middleware to protect routes based on authentication status. The auth middleware verifies that the user is authenticated using the default guard specified in the auth configuration. You can also specify a specific guard for a route using the guard middleware. 36 | 37 | 38 | Route::get('/dashboard', function () { 39 | // Only authenticated users can access this route 40 | })->middleware('auth'); 41 | 42 | Route::get('/api/resource', function () { 43 | // Only authenticated users can access this route with the 'api' guard 44 | })->middleware('auth:api'); 45 | In the example above, the '/dashboard' route is protected by the auth middleware, which ensures that only authenticated users can access it. The '/api/resource' route is protected by the auth:api middleware, which uses the 'api' guard for authentication. 46 | 47 | Multiple Guards: 48 | Laravel allows you to define and use multiple guards simultaneously. This can be useful when you have different authentication methods or user types in your application. 49 | 50 | 51 | if (Auth::guard('web')->check()) { 52 | // Web guard authentication 53 | } 54 | 55 | if (Auth::guard('api')->check()) { 56 | // API guard authentication 57 | } 58 | In the code snippet above, the check method is used to determine if a user is authenticated using a specific guard. You can switch between guards by specifying the guard's name when retrieving the guard instance. 59 | 60 | Guards in Laravel provide a flexible and powerful way to authenticate users and protect different parts of your application. By configuring guards, authenticating users 61 | 62 | 63 | */ -------------------------------------------------------------------------------- /understanding_laravel/php_premier/understanding_namespace.js: -------------------------------------------------------------------------------- 1 | /* 2 | Namespaces in Laravel provide a way to organize and group related classes or files together. They help prevent naming conflicts and make it easier to locate and manage your code. Here's a step-by-step explanation of how namespaces work in Laravel: 3 | 4 | Namespace Declaration: 5 | In Laravel, namespaces are declared at the beginning of each PHP file using the namespace keyword. The namespace declaration should reflect the directory structure of the file. 6 | 7 | 8 | namespace App\Http\Controllers; 9 | 10 | class UserController 11 | { 12 | // Controller code... 13 | } 14 | In the example above, the UserController class is declared within the App\Http\Controllers namespace. This means that the file is located in the app/Http/Controllers directory relative to the Laravel project root. 15 | 16 | Namespace Usage: 17 | When using a class or function from another namespace, you need to specify the namespace or import the class using the use keyword. This allows you to refer to the class directly without fully qualifying the namespace each time. 18 | 19 | 20 | namespace App\Http\Controllers; 21 | 22 | use App\Models\User; 23 | use App\Services\EmailService; 24 | 25 | class UserController 26 | { 27 | public function show(User $user, EmailService $emailService) 28 | { 29 | // Controller code... 30 | } 31 | } 32 | In the code snippet above, the User class from the App\Models namespace and the EmailService class from the App\Services namespace are imported using the use keyword. This allows you to use these classes directly within the UserController without specifying the full namespace. 33 | 34 | Sub-namespaces: 35 | Laravel supports sub-namespaces, which allow you to further organize your code within a namespace. Sub-namespaces are represented by additional levels in the namespace declaration and directory structure. 36 | 37 | 38 | namespace App\Http\Controllers\Admin; 39 | 40 | class UserController 41 | { 42 | // Controller code... 43 | } 44 | In this example, the UserController class is declared within the App\Http\Controllers\Admin namespace. This means that the file should be located in the app/Http/Controllers/Admin directory relative to the Laravel project root. 45 | 46 | Namespace Aliasing: 47 | Laravel provides a convenient way to alias namespaces using the as keyword. This allows you to assign a shorter, more readable alias to a namespace. 48 | 49 | 50 | namespace App\Http\Controllers; 51 | 52 | use App\Models\User as UserModel; 53 | 54 | class UserController 55 | { 56 | public function show(UserModel $user) 57 | { 58 | // Controller code... 59 | } 60 | } 61 | In the code above, the UserModel class is an alias for the App\Models\User namespace. This allows you to use the shorter UserModel alias within the UserController. 62 | 63 | Namespaces in Laravel help organize and structure your codebase, prevent naming conflicts, and improve code readability. They are especially useful in larger projects with multiple classes and directories. 64 | 65 | I hope this detailed explanation helps you understand the concept of namespaces in Laravel! Let me know if you have any further questions. 66 | 67 | */ -------------------------------------------------------------------------------- /understanding_laravel/php_premier/understanding_notifiable.js: -------------------------------------------------------------------------------- 1 | /* 2 | The Notifiable trait in Laravel is used to add notification support to a class. It allows the class to send notifications through various channels such as email, SMS, Slack, and more. 3 | 4 | Here's an example to demonstrate the concept of Notifiable in Laravel: 5 | 6 | First, let's assume we have a User model in our application. To make the User model notifiable, you need to use the Notifiable trait: 7 | 8 | use Illuminate\Notifications\Notifiable; 9 | use Illuminate\Foundation\Auth\User as Authenticatable; 10 | 11 | class User extends Authenticatable 12 | { 13 | use Notifiable; 14 | 15 | // Rest of the class implementation 16 | } 17 | By including the Notifiable trait in the User model, you enable notification support for that model. 18 | 19 | Once the Notifiable trait is added, you can start using the notification functionality. For example, to send an email notification to a user, you can call the notify() method on an instance of the User model: 20 | 21 | $user = User::find(1); 22 | $user->notify(new OrderShippedNotification($order)); 23 | In the above code, we retrieve a user with the ID of 1 from the database, and then we call the notify() method on it. We pass an instance of the OrderShippedNotification class, which represents the notification we want to send. 24 | 25 | To create a notification, you can use the make:notification Artisan command: 26 | 27 | php artisan make:notification OrderShippedNotification 28 | This command generates a new notification class in the app/Notifications directory. You can define the logic for the notification in this class. 29 | 30 | Let's assume we have the OrderShippedNotification class generated. Here's an example implementation: 31 | 32 | use Illuminate\Bus\Queueable; 33 | use Illuminate\Contracts\Queue\ShouldQueue; 34 | use Illuminate\Notifications\Notification; 35 | use Illuminate\Notifications\Messages\MailMessage; 36 | 37 | class OrderShippedNotification extends Notification 38 | { 39 | use Queueable; 40 | 41 | protected $order; 42 | 43 | public function __construct($order) 44 | { 45 | $this->order = $order; 46 | } 47 | 48 | public function via($notifiable) 49 | { 50 | return ['mail']; 51 | } 52 | 53 | public function toMail($notifiable) 54 | { 55 | return (new MailMessage) 56 | ->subject('Order Shipped') 57 | ->line('Your order has been shipped.') 58 | ->action('View Order', url('/orders/' . $this->order->id)) 59 | ->line('Thank you for using our application!'); 60 | } 61 | } 62 | In the OrderShippedNotification class, we implement the via() method to specify the channels through which the notification should be sent. In this case, we're using the mail channel. 63 | 64 | We also implement the toMail() method to define the email content for the notification. Here, we create a MailMessage instance and customize the subject, body, and any additional actions. 65 | 66 | By default, the Notifiable trait supports various notification channels, including mail, database, broadcast, Slack, SMS, and more. You can define multiple channels in the via() method and implement corresponding methods like toMail(), toDatabase(), etc., based on your requirements. 67 | 68 | Using the Notifiable trait in Laravel allows you to easily send notifications to users through different channels. It provides a convenient way to keep users informed about important events or updates in your application. 69 | 70 | I hope this explanation helps you understand the concept of the Notifiable trait in Laravel. 71 | 72 | */ -------------------------------------------------------------------------------- /understanding_laravel/php_premier/understanding_resource.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, Resources are a powerful way to transform and format data before sending it as a response. They allow you to define the structure and presentation of your API resources in a consistent and reusable manner. 3 | 4 | Here's an example to demonstrate the concept of Resources in Laravel: 5 | 6 | Let's assume we have a Task model that represents tasks in our application. To create a resource for the Task model, we can use the make:resource Artisan command: 7 | 8 | php artisan make:resource TaskResource 9 | This command generates a new resource class in the app/Http/Resources directory. You can define how the data should be transformed and presented in this class. 10 | 11 | Once the TaskResource class is generated, you can define its structure and transformation logic. Here's an example implementation: 12 | 13 | namespace App\Http\Resources; 14 | 15 | use Illuminate\Http\Resources\Json\JsonResource; 16 | 17 | class TaskResource extends JsonResource 18 | { 19 | /** 20 | * Transform the resource into an array. 21 | * 22 | * @param \Illuminate\Http\Request $request 23 | * @return array 24 | */ 25 | // public function toArray($request) { 26 | // return [ 27 | // 'id' => $this -> id, 28 | // 'name' => $this -> name, 29 | // 'is_completed' => (bool) $this -> is_completed, 30 | // 'created_at' => $this -> created_at, 31 | // 'updated_at' => $this -> updated_at, 32 | // ]; 33 | // } 34 | // } 35 | 36 | // In the TaskResource class, we extend the JsonResource class provided by Laravel.This base class provides helpful methods for transforming and formatting the data. 37 | 38 | // The toArray() method is the most important method in a resource class. It defines how the data should be transformed into an array structure.In this example, we include the id, name, is_completed, created_at, and updated_at attributes of the Task model. 39 | 40 | // Now, let's use the TaskResource in a controller to transform a Task model instance before returning it as a response. Here's an example: 41 | 42 | // use App\Http\Resources\TaskResource; 43 | // use App\Models\Task; 44 | 45 | // class TaskController extends Controller { 46 | // public function show($id) { 47 | // $task = Task:: find($id); 48 | 49 | // return new TaskResource($task); 50 | // } 51 | // } 52 | // In the show() method of the TaskController, we retrieve a Task model instance from the database and then pass it to the TaskResource class. By wrapping the model instance with the TaskResource, we instruct Laravel to transform the data according to the resource's definition before returning the response. 53 | 54 | // When a request is made to the show() method, Laravel automatically applies the transformation defined in the TaskResource class. The response will be formatted as an array structure like this: 55 | 56 | // { 57 | // "id": 1, 58 | // "name": "Example Task", 59 | // "is_completed": true, 60 | // "created_at": "2022-01-01 12:00:00", 61 | // "updated_at": "2022-01-02 09:30:00" 62 | // } 63 | // By using Resources in Laravel, you can easily customize the output format of your API responses.Resources provide a consistent and reusable way to transform data, allowing you to separate the data representation from the models themselves. 64 | 65 | // I hope this explanation helps you understand the concept of Resources in Laravel. 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /understanding_laravel/php_premier/understanding_softDeletes.js: -------------------------------------------------------------------------------- 1 | /* 2 | The SoftDeletes feature in Laravel allows you to perform "soft" deletion of records in a database. Soft deletion means that instead of permanently deleting a record, it is marked as deleted by setting a flag in the database. This allows for easy retrieval of deleted records if needed. 3 | 4 | Here's an example to demonstrate the concept of SoftDeletes in Laravel: 5 | 6 | First, you need to add the deleted_at column to the table associated with the model. This column will be used to store the timestamp when a record is soft deleted. You can achieve this by creating a new migration or modifying an existing one. For example, let's assume we have a tasks table: 7 | 8 | use Illuminate\Database\Migrations\Migration; 9 | use Illuminate\Database\Schema\Blueprint; 10 | use Illuminate\Support\Facades\Schema; 11 | 12 | class AddDeletedAtColumnToTasksTable extends Migration 13 | { 14 | public function up() 15 | { 16 | Schema::table('tasks', function (Blueprint $table) { 17 | $table->timestamp('deleted_at')->nullable(); 18 | }); 19 | } 20 | 21 | public function down() 22 | { 23 | Schema::table('tasks', function (Blueprint $table) { 24 | $table->dropColumn('deleted_at'); 25 | }); 26 | } 27 | } 28 | In the above migration, we add a nullable deleted_at column to the tasks table. This column will be used to store the deletion timestamp when a task is soft deleted. 29 | 30 | Next, in the model class associated with the table, you need to use the SoftDeletes trait: 31 | 32 | use Illuminate\Database\Eloquent\Model; 33 | use Illuminate\Database\Eloquent\SoftDeletes; 34 | 35 | class Task extends Model 36 | { 37 | use SoftDeletes; 38 | 39 | // Rest of the class implementation 40 | } 41 | By including the SoftDeletes trait in the Task model, you enable the soft deletion functionality for that model. 42 | 43 | Once the SoftDeletes trait is added, you can start using the soft deletion features. For example, to soft delete a record, you can call the delete() method on an instance of the model: 44 | 45 | $task = Task::find(1); 46 | $task->delete(); 47 | In the above code, we retrieve a task with the ID of 1 from the database and then call the delete() method on it. This will soft delete the task, setting the deleted_at timestamp for that record. 48 | 49 | To retrieve both non-deleted and soft-deleted records, you can use the withTrashed() method on a query: 50 | 51 | $tasks = Task::withTrashed()->get(); 52 | The withTrashed() method retrieves all records, including soft-deleted ones. This allows you to access both active and deleted records. 53 | 54 | If you want to retrieve only the soft-deleted records, you can use the onlyTrashed() method: 55 | 56 | $deletedTasks = Task::onlyTrashed()->get(); 57 | The onlyTrashed() method filters the query to return only the soft-deleted records. 58 | 59 | To restore a soft-deleted record, you can use the restore() method: 60 | 61 | $task = Task::withTrashed()->find(1); 62 | $task->restore(); 63 | The restore() method restores a soft-deleted record, removing the deleted_at timestamp and making it active again. 64 | 65 | Using the SoftDeletes feature in Laravel allows you to retain deleted records in the database while providing the flexibility to restore them if needed. It provides a simple and convenient way to handle soft deletion functionality in your application. 66 | 67 | I hope this explanation helps you understand the 68 | */ -------------------------------------------------------------------------------- /understanding_laravel/pub_sub_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/pub_sub_pattern.png -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/1_query_builder_helper_methods.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 👌Retrieving a single row 4 | 5 | 👌Laravel, the query builder provides several helpful methods for retrieving a single row from a database table. Let me walk you through a few of them with code examples. 6 | 7 | 👌first(): This method retrieves the first record matching the query criteria. The first() method return an object, which can be accessed using the arrow notation 8 | 9 | $user = DB::table('users')->where('status', 'active')->first(); 10 | In this example, the first() method is used to retrieve the first active user from the "users" table. 11 | 12 | 👌find(): This method retrieves a record by its primary key.The find() method is used to retrieve a single record by its primary key. 13 | 14 | $user = DB::table('users')->find(1); 15 | In this case, the find(1) method is used to retrieve the user record with a primary key of 1. 16 | 17 | 👌firstWhere(): This method retrieves the first record matching the specified column and value. 18 | 19 | $user = DB::table('users')->firstWhere('name', 'John'); 20 | Here, the firstWhere('name', 'John') method is used to retrieve the first user record with the name "John". 21 | 22 | 👌value(): This method retrieves a single value from a specific column in the first matching record.The value() method is used to retrieve a single value from a result set. 23 | 24 | $email = DB::table('users')->where('name', 'John')->value('email'); 25 | In this example, the value('email') method retrieves the email value for the user with the name "John". 26 | 27 | These are just a few examples of the query builder methods available in Laravel for retrieving a single row from a database table. You can mix and match these methods with other query conditions to suit your specific requirements. 28 | 29 | */ 30 | 31 | /* 32 | 👌 Retrieving a list of column values: 33 | 34 | In Laravel's query builder, you can retrieve a list of column values from a database table using various methods. Let me guide you through some of the commonly used methods with code examples. 35 | 36 | pluck(): This method retrieves a list of values from a single column in the table. 37 | 38 | $names = DB::table('users')->pluck('name'); 39 | In this example, the pluck('name') method retrieves an array containing all the values from the "name" column of the "users" table. 40 | 41 | select(): This method allows you to specify multiple columns to retrieve from the table. 42 | 43 | $users = DB::table('users')->select('name', 'email')->get(); 44 | Here, the select('name', 'email') method is used to retrieve the "name" and "email" columns from the "users" table. 45 | 46 | distinct(): This method retrieves a list of distinct values from a column. 47 | 48 | $categories = DB::table('products')->distinct()->pluck('category'); 49 | In this example, the distinct() method is used before pluck('category') to retrieve a list of distinct values from the "category" column of the "products" table. 50 | 51 | lists(): Note: The lists() method was deprecated in Laravel 5.3 and removed in Laravel 5.4. It is no longer available. 52 | 53 | These are some examples of how you can retrieve a list of column values using Laravel's query builder. You can combine these methods with other query conditions and use them according to your specific needs. 54 | 55 | */ -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder.js: -------------------------------------------------------------------------------- 1 | /* 2 | Laravel's query builder is a set of classes and methods that provide 3 | a simple and elegant way to interact with databases 4 | 5 | 6 | The first() method returns an object, which can be accessed using 7 | the arrow notation 8 | 9 | The value() method is used to retrieve a single value from a result set. 10 | 11 | The find() method is used to retrieve a single record by its primary key 12 | 13 | The pluck() method is used to retrieve a single columns value from the first 14 | result of a query. 15 | 16 | insertOrIgnore() method is a method that allows you to insert data into a 17 | database table only if the data doesn't already exist in the table 18 | 19 | The upsert() method on the query builder in laravel is a powerful tool for 20 | performing insert or update operations on large datasets 21 | 22 | The insertGetId() method allows you to insert a new record into a table 23 | and retrieve its id in a single query. 24 | 25 | 26 | */ -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/10_removing_existing_ordering.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉Removing Existing Ordering : 3 | 👉$posts = DB::table('posts') 4 | ->orderBy('is_published'); 5 | 6 | $unorderedPosts = $posts->reorder()->get(); 7 | 8 | dd($unorderedPosts); 9 | 10 | 11 | 👉 $posts = DB::table('posts') 12 | ->orderBy('is_published'); 13 | 14 | $unorderedPosts = $posts->reorder('title', 'desc')->get(); 15 | dd($unorderedPosts); 16 | 17 | 18 | */ 19 | 20 | 21 | // The reorder() method allows you to change the order in which the query results are returned by modifying the ORDER BY clause of the SQL query. 22 | 23 | // Here's an explanation of the reorder() method with some code examples: 24 | 25 | // Basic usage: 26 | 27 | 28 | // $query = DB:: table('users') -> orderBy('name') -> reorder('email'); 29 | 30 | // In this example, we start with a query that orders the results by the name column.Then, we use the reorder() method to change the ordering to the email column. 31 | 32 | // Reordering in descending order: 33 | 34 | 35 | // $query = DB:: table('users') -> orderBy('name') -> reorder('email', 'desc'); 36 | 37 | // This example is similar to the previous one, but we pass a second parameter to the reorder() method, indicating that the ordering should be in descending order. 38 | 39 | // Combining with other query builder methods: 40 | 41 | 42 | // $query = DB:: table('users') -> where('status', 'active') -> orderBy('name') -> reorder('email'); 43 | 44 | // In this example, we combine the reorder() method with the where() method to filter the results by the status column.The reorder() method is called after the orderBy() method to change the ordering. 45 | 46 | // Using a subquery for reordering: 47 | 48 | 49 | // $subquery = DB:: table('orders') -> select('user_id') -> orderBy('created_at', 'desc'); 50 | 51 | // $query = DB:: table('users') -> whereIn('id', $subquery) -> reorder('email'); 52 | 53 | // Here, we use a subquery to fetch the latest user_id values from the orders table.Then, we pass the subquery as a parameter to the whereIn() method to filter the results in the users table.Finally, we use the reorder() method to order the results by the email column. 54 | 55 | // That's a brief overview of the reorder() method in the Laravel query builder. It provides flexibility in modifying the ordering of query results, allowing you to adjust it based on your application's needs.Feel free to experiment with different combinations of methods to achieve the desired result in your code. 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/11_using_the_paginate_method.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉 Pagination is a technique that allows us to divide a large set of data 3 | into smaller chunks of pages. 4 | 5 | 👉 Paginate Method: 6 | 👉$posts = DB::table( 'posts' )->paginate( 10 ); 7 | dd($posts); 8 | 9 | 👉 $posts = DB::table( 'posts' )->paginate( 10, ['*'], 'p', 1 ); 10 | dd($posts); 11 | 12 | 👉 $posts = DB::table( 'posts' )->paginate( 10, ['*'], 'p', 1 ); 13 | 14 | return view( 'posts.index', compact( 'posts' ) ); 15 | 16 | 👉 $posts = DB::table( 'posts' )->paginate( 10); 17 | 18 | return view( 'posts.index', compact( 'posts' ) ); 19 | 20 | */ 21 | 22 | 23 | // The paginate() method is a convenient way to retrieve a paginated set of results from a database query using Laravel's query builder. It allows you to split the results into multiple pages, making it easier to handle large datasets. Here's how you can use it: 24 | 25 | // Start by constructing your initial query using the query builder methods(select(), from(), where(), etc.).Here's an example: 26 | 27 | // use Illuminate\Support\Facades\DB; 28 | 29 | // $results = DB:: table('users') 30 | // -> select('id', 'name', 'email') 31 | // -> where('status', 'active') 32 | // -> orderBy('name', 'asc') 33 | // -> paginate(10); // 10 results per page 34 | 35 | // In this example, we're querying the users table, selecting the id, name, and email columns. We're filtering the results to only include active users, ordering them by name in ascending order, and then paginating the results with 10 results per page. 36 | 37 | // Once you've defined your query, you can use the paginate() method to retrieve the paginated results. This method returns an instance of the LengthAwarePaginator class, which contains the results as well as additional pagination information. Here's an example of how you can access and iterate over the paginated results: 38 | 39 | // foreach($results as $user) { 40 | // echo $user -> name; 41 | // } 42 | 43 | // In this loop, we're accessing the name property of each user in the paginated results. 44 | 45 | // You can also access additional pagination information provided by the LengthAwarePaginator class. Some common methods you might find useful include currentPage(), lastPage(), total(), and perPage().Here's an example of how to use them: 46 | 47 | // echo "Current Page: ".$results -> currentPage(); // Get the current page number 48 | // echo "Last Page: ".$results -> lastPage(); // Get the last page number 49 | // echo "Total Results: ".$results -> total(); // Get the total number of results 50 | // echo "Results Per Page: ".$results -> perPage(); // Get the number of results per page 51 | 52 | // These methods allow you to access information about the pagination state and adjust your application's UI or logic accordingly. 53 | 54 | // That's the basic usage of the paginate() method in Laravel's query builder.Remember to replace 'users' with the name of your actual table and adjust the query builder methods as needed to suit your specific requirements. 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/12_using_the_simplePaginate_method.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉simplePaginate() Method : 3 | 4 | 👉 $posts = DB::table('posts')->simplePaginate(10); 5 | 6 | return view('posts.index', compact('posts')); 7 | 8 | 9 | */ 10 | 11 | 12 | // The simplePaginate() method is a convenient way to paginate query results in Laravel.It provides a simplified pagination result without the need for a detailed pagination view.It's useful when you want to display paginated results without the additional pagination links, like "previous" and "next" buttons. 13 | 14 | // Here's an example of how to use the simplePaginate() method in Laravel: 15 | 16 | 17 | // use App\Models\User; 18 | 19 | // $users = User:: where('active', true) 20 | // -> orderBy('name') 21 | // -> simplePaginate(10); 22 | 23 | // In this example, we're querying the users table for active users, ordering them by name, and paginating the results with a page size of 10. 24 | 25 | // The simplePaginate() method returns an instance of the LengthAwarePaginator class, which provides a few useful methods and properties.For example, you can access the paginated items using the items() method: 26 | 27 | 28 | // foreach($users -> items() as $user) { 29 | // echo $user -> name; 30 | // } 31 | 32 | // To display the pagination links in your view, you can use the links() method: 33 | 34 | 35 | // { { $users -> links() } } 36 | 37 | // This will render a simple pagination view that only includes the current page number. 38 | 39 | // If you want to customize the view used by the simplePaginate() method, you can publish the Laravel pagination views and modify them according to your needs.To do this, run the following command in your terminal: 40 | 41 | 42 | // php artisan vendor: publish--tag = laravel - pagination 43 | 44 | // This will publish the pagination views to the resources / views / vendor / pagination directory, where you can modify the simple - bootstrap - 4.blade.php file or create your own custom view. 45 | 46 | // And that's it! You now know how to use the simplePaginate() method in Laravel's query builder to paginate query results without the additional pagination links.Remember, this method is suitable for simpler pagination scenarios where you don't need a more advanced pagination UI. 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/13_using_the_cursorPaginate_method.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉cursorPaginate() method : 3 | 4 | 👉 $posts = DB::table('posts') 5 | ->orderBy('id') 6 | ->cursorPaginate(10); 7 | 8 | return view('posts.index', compact('posts')); 9 | 10 | 11 | */ 12 | 13 | 14 | 15 | // The cursorPaginate() method is a convenient way to paginate large result sets efficiently using database cursors.It is available in Laravel 7 and above.It allows you to fetch records from a database table in small "chunks" using cursors, rather than loading the entire result set into memory. 16 | 17 | // Here's how you can use cursorPaginate() with code examples: 18 | 19 | // Step 1: Setting up the Model 20 | // First, you'll need to have a model that represents the table you want to paginate. Let's assume we have a User model representing the users table.Make sure the model extends the Illuminate\Database\Eloquent\Model class. 21 | 22 | // Step 2: Using the cursorPaginate() method 23 | // In your controller or wherever you want to paginate the results, you can use the cursorPaginate() method on the query builder to fetch the paginated records. 24 | 25 | 26 | // use App\Models\User; 27 | // use Illuminate\Http\Request; 28 | 29 | // public function index(Request $request) { 30 | // $perPage = $request -> input('per_page', 10); // Number of records per page 31 | 32 | // $users = User:: query() -> cursorPaginate($perPage); 33 | 34 | // return view('users.index', ['users' => $users]); 35 | // } 36 | 37 | // In the example above, we're using the User model to query the users table and calling the cursorPaginate() method to fetch the paginated results. The $perPage variable represents the number of records per page, and we're fetching it from the request using the input() method. 38 | 39 | // Step 3: Displaying the Paginated Results 40 | // In your view file(users.index.blade.php in this case), you can loop through the $users variable to display the paginated results: 41 | 42 | 43 | // @foreach($users as $user) 44 | //

{{ $user-> name}}

45 | // @endforeach 46 | 47 | // { { $users -> links() } } 48 | 49 | // The links() method generates the pagination links, such as "Previous" and "Next," which you can display at the bottom of the page. 50 | 51 | // That's it! With these steps, you can use the cursorPaginate() method to efficiently paginate large result sets using cursors in Laravel's query builder. 52 | 53 | // Please note that cursor pagination is most suitable for scenarios where you're paginating large data sets. If you're dealing with a smaller number of records, you can use the regular paginate() method, which loads the entire result set into memory. 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/1_database_transactions.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉Database Transaction 3 | Database transactions are a way of ensuring data, consistency and integrity in your application. 4 | 5 | It basically allows you to ensure that the series of database operations are performed as a single unit of work 6 | 7 | This can be useful in situations where you need to perform multiple database operations together and want to ensure that they are all succeeded or failed as a single unit. 8 | 9 | 👉 Example 10 | 11 | What I want to do right now is adding a new column to our users table which will indicate the user's balance whenever a user one will send money to user two. 12 | 13 | We basically have to decrease the balance of user one and increase the balance of user 2 in 1 single query. 14 | 15 | We don't have that much data inside our tables so we can modify the user's migration and let's actually do that 16 | 17 | So right below our password column, we're going to define a new column through our table object where 18 | 19 | */ 20 | 21 | 22 | 23 | 24 | // Database transactions are crucial when you need to perform multiple database operations as a single atomic unit, ensuring that either all the operations succeed or none of them are applied.Laravel provides a convenient way to work with transactions using the query builder. 25 | 26 | // To get started, let's assume you have a Laravel project set up with a configured database connection. First, make sure you have imported the necessary classes at the top of your file: 27 | 28 | 29 | // use Illuminate\Support\Facades\DB; 30 | // use Illuminate\Support\Facades\Log; 31 | // Now, let's dive into the concept of transactions with Laravel query builder. 32 | 33 | // Beginning a Transaction: 34 | // To start a transaction, you can use the beginTransaction method provided by the DB facade: 35 | 36 | // DB:: beginTransaction(); 37 | // Performing Database Operations: 38 | // Next, you can perform your database operations within the transaction using the query builder methods.For example, let's say we want to update a user's email address and insert a new record in another table: 39 | 40 | // try { 41 | // DB:: table('users') 42 | // -> where('id', 1) 43 | // -> update(['email' => 'newemail@example.com']); 44 | 45 | // DB:: table('orders') -> insert([ 46 | // 'user_id' => 1, 47 | // 'amount' => 100.00, 48 | // ]); 49 | 50 | // // Additional database operations 51 | 52 | // DB:: commit(); // If all operations succeed, commit the transaction 53 | // } catch (\Exception $e) { 54 | // DB:: rollback(); // If an exception occurs, rollback the transaction 55 | // Log:: error('Transaction failed: '.$e -> getMessage()); 56 | // } 57 | 58 | // Committing or Rolling Back the Transaction: 59 | // After performing the database operations, you can either commit the transaction or roll it back.If all the operations within the transaction have succeeded, you should call the commit method.Otherwise, if an exception occurs or you explicitly want to cancel the transaction, you can call the rollback method. 60 | 61 | // Exception Handling: 62 | // Wrap your transaction logic within a try-catch block to catch any exceptions that might occur during the transaction.In the example above, we catch the \Exception class, but you can customize it to suit your needs. 63 | 64 | // By wrapping your database operations within a transaction, Laravel ensures that any failure during the transaction will cause a rollback, reverting all changes made within that transaction.This way, you maintain the integrity and consistency of your data. 65 | 66 | // Remember to handle exceptions appropriately and log any errors for debugging purposes. 67 | 68 | // That's it! You now know how to use database transactions in Laravel query builder. Transactions are incredibly useful when dealing with critical operations, such as updating multiple tables or performing complex data manipulations. 69 | 70 | // Feel free to ask if you have any further questions or need additional assistance! 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/8_limit_offset_through_query_builder.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉 Limit and Offset through query builder: 3 | 4 | 👉limit() 5 | 6 | DB:: table('posts') -> limit(10) -> get(); 7 | 8 | 👉 offset() 9 | 10 | DB:: table('posts') -> offset(10) -> limit(10) -> get() 11 | 12 | 13 | */ 14 | 15 | 16 | // Certainly! I'd be happy to help you understand the limit() and offset() methods in the Laravel query builder. These methods are used to control the number of records returned and to skip a certain number of records, respectively. Let's dive into each of them with code examples. 17 | 18 | // limit(): The limit() method is used to specify the maximum number of records to be retrieved from the database.It restricts the result set to the specified limit.Here's an example: 19 | 20 | // $users = DB:: table('users') 21 | // -> select('name', 'email') 22 | // -> limit(5) 23 | // -> get(); 24 | 25 | // In the example above, we're querying the "users" table and selecting only the "name" and "email" columns. The limit(5) method ensures that we retrieve a maximum of 5 records from the table. 26 | 27 | // offset(): The offset() method is used to skip a certain number of records from the beginning of the result set.It is commonly used in combination with limit() to implement pagination.Here's an example: 28 | 29 | // $users = DB:: table('users') 30 | // -> select('name', 'email') 31 | // -> offset(10) 32 | // -> limit(5) 33 | // -> get(); 34 | 35 | // In this example, we're skipping the first 10 records (offset(10)) and retrieving the next 5 records (limit(5)). This is useful when you want to fetch data for a specific page of a paginated result. 36 | 37 | // By combining limit() and offset() methods, you can fetch records in smaller chunks or implement pagination efficiently.For example, in a web application, you can use limit() to determine how many records to display per page, and offset() to calculate the appropriate offset based on the current page number. 38 | 39 | // It's important to note that these methods can be used with other query builder methods such as where(), orderBy(), and groupBy() to further refine your queries. 40 | 41 | // I hope this explanation clarifies the usage of limit() and offset() in the Laravel query builder.If you have any further questions, feel free to ask! 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_advance_topics/9_conditional_clause.js: -------------------------------------------------------------------------------- 1 | /* 2 | 👉 Conditional Clause : 3 | 👉 DB::table('posts') 4 | ->when(function ($query) { 5 | return $query->where('is_published', true); 6 | })->get(); 7 | 8 | 9 | */ 10 | 11 | 12 | 13 | 14 | 15 | // In Laravel, the when() method is used to conditionally apply constraints to a query based on a given condition.It allows you to dynamically add query constraints without writing repetitive if statements. 16 | 17 | // The when() method takes two arguments: the condition and a closure that defines the constraints to be applied when the condition is true.If the condition evaluates to false, the closure will not be executed, and the query will continue without any additional constraints. 18 | 19 | // Here's an example to demonstrate how the when() method can be used: 20 | 21 | 22 | // $users = DB:: table('users') 23 | // -> when($request -> has('active'), function ($query) { 24 | // return $query -> where('active', true); 25 | // }) 26 | // -> when($request -> has('role'), function ($query) use($request) { 27 | // return $query -> where('role', $request -> input('role')); 28 | // }) 29 | // -> get(); 30 | 31 | // In this example, we have a query to fetch users from the users table.We want to conditionally apply constraints based on the presence of certain parameters in the request. 32 | 33 | // The first when() method checks if the active parameter exists in the request.If it does, the closure will be executed, and a where condition will be added to the query to filter active users. 34 | 35 | // The second when() method checks if the role parameter exists in the request.If it does, the closure will be executed, and a where condition will be added to the query to filter users based on their role. 36 | 37 | // By using the when() method, we can avoid writing multiple if statements and dynamically apply constraints based on the conditions provided.This leads to more readable and maintainable code. 38 | 39 | // It's important to note that the when() method is available on both the Illuminate\Database\Query\Builder and Illuminate\Database\Eloquent\Builder classes, so you can use it with both raw queries and Eloquent queries. 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_methods.js: -------------------------------------------------------------------------------- 1 | /* 2 | Laravel provides a powerful and intuitive query builder that allows you to build database queries using a fluent interface. Here are some commonly used query builder methods in Laravel: 3 | 4 | select: Specifies the columns to retrieve from the database. 5 | from: Specifies the table to query. 6 | where: Adds a basic where clause to the query. 7 | orWhere: Adds an "or" where clause to the query. 8 | whereIn / whereNotIn: Adds a where clause to check if a column's value is in a given array or not in a given array. 9 | whereNull / whereNotNull: Adds a where clause to check for null values or non-null values. 10 | orderBy: Specifies the column to order the results by. 11 | groupBy: Groups the query results by a column. 12 | having: Adds a "having" clause to the query. 13 | join: Performs an inner join with another table. 14 | leftJoin / rightJoin: Performs a left join or right join with another table. 15 | count: Retrieves the number of rows matching the query. 16 | first: Retrieves the first record matching the query. 17 | get: Retrieves all records matching the query. 18 | insert: Inserts a new record into the database. 19 | update: Updates existing records in the database. 20 | delete: Deletes records from the database. 21 | These are just some of the commonly used query builder methods in Laravel. There are many more methods available that can help you construct complex and powerful database queries. I recommend referring to the official Laravel documentation for a comprehensive list of all query builder methods and their usage: https://laravel.com/docs/query-builder 22 | */ 23 | 24 | /* 25 | 26 | Here are some additional query builder methods in Laravel: 27 | 28 | orWhereIn / orWhereNotIn: Adds an "or where" clause to check if a column's value is in a given array or not in a given array. 29 | whereBetween / whereNotBetween: Adds a where clause to check if a column's value is between two values or not between two values. 30 | whereDate / whereMonth / whereDay / whereYear: Adds a where clause to check for specific dates or parts of a date (month, day, year). 31 | orWhereDate / orWhereMonth / orWhereDay / orWhereYear: Adds an "or where" clause to check for specific dates or parts of a date. 32 | whereColumn: Adds a where clause to compare two columns. 33 | orWhereColumn: Adds an "or where" clause to compare two columns. 34 | selectRaw: Adds a raw select expression to the query. 35 | orderByRaw: Adds a raw order by expression to the query. 36 | groupByRaw: Adds a raw group by expression to the query. 37 | havingRaw: Adds a raw having clause to the query. 38 | joinSub: Performs a join with a subquery. 39 | union: Performs a union query with another query. 40 | exists / doesntExist: Adds a subquery where clause to check for the existence or non-existence of related records. 41 | with: Eager loads relationships for the query. 42 | withCount: Eager loads relationships and includes a count of related records. 43 | pluck: Retrieves a single column's value from the first result of the query. 44 | chunk: Processes the query results in chunks to conserve memory. 45 | These are some additional query builder methods that can help you manipulate and retrieve data from the database in Laravel. Remember to consult the Laravel documentation for detailed explanations and examples of these methods: https://laravel.com/docs/query-builder 46 | 47 | */ 48 | 49 | /* 50 | Here are a few more query builder methods in Laravel: 51 | 52 | orWhereBetween / orWhereNotBetween: Adds an "or where" clause to check if a column's value is between two values or not between two values. 53 | whereTime / orWhereTime: Adds a where clause to check for a specific time. 54 | whereDateNotBetween / orWhereDateNotBetween: Adds a where clause to check if a column's value is not between two dates. 55 | whereNested: Adds a nested where clause. 56 | orWhereNested: Adds a nested "or where" clause. 57 | whereExists / orWhereExists: Adds a where clause to check for the existence of a subquery. 58 | whereNotExists / orWhereNotExists: Adds a where clause to check for the non-existence of a subquery. 59 | orWhereColumnNot: Adds an "or where" clause to compare two columns for inequality. 60 | havingBetween / havingNotBetween: Adds a having clause to check if a column's aggregate value is between two values or not between two values. 61 | havingRaw: Adds a raw having clause to the query. 62 | offset: Sets the number of records to skip from the beginning of the result set. 63 | limit: Limits the number of records to retrieve. 64 | skip: Alias for the offset method. 65 | take: Alias for the limit method. 66 | distinct: Retrieves only distinct records from the query. 67 | sharedLock: Adds a shared lock to the query. 68 | lockForUpdate: Adds a "for update" lock to the query. 69 | These additional query builder methods in Laravel can help you further customize and fine-tune your database queries. Remember to refer to the Laravel documentation for more detailed explanations and examples: https://laravel.com/docs/query-builder 70 | */ -------------------------------------------------------------------------------- /understanding_laravel/qurey_builder/query_builder_methods_description.js: -------------------------------------------------------------------------------- 1 | // Let's dive into the query builder methods in Laravel with detailed explanations and code examples. I'll walk you through various scenarios and demonstrate how to use the query builder methods effectively. 2 | 3 | // Selecting Columns: 4 | // The select method is used to specify the columns to retrieve from the database.You can pass column names as arguments or an array of column names. 5 | 6 | 7 | // $users = DB:: table('users') 8 | // -> select('name', 'email') 9 | // -> get(); 10 | 11 | // Filtering Records: 12 | // The where method allows you to add a basic where clause to the query.You can specify the column, operator, and value to filter the records. 13 | 14 | 15 | // $users = DB:: table('users') 16 | // -> where('age', '>', 18) 17 | // -> get(); 18 | 19 | // You can also chain multiple where clauses or use the orWhere method for an "or" condition. 20 | 21 | 22 | // $users = DB:: table('users') 23 | // -> where('age', '>', 18) 24 | // -> orWhere('city', 'London') 25 | // -> get(); 26 | 27 | // Retrieving Records: 28 | // The get method is used to retrieve all records that match the query.You can also use the first method to retrieve only the first matching record. 29 | 30 | 31 | // $users = DB:: table('users') -> get(); 32 | 33 | // $user = DB:: table('users') -> where('id', 1) -> first(); 34 | // Sorting Records: 35 | // The orderBy method is used to specify the column to order the results by.You can also chain multiple orderBy clauses for multi - level sorting. 36 | 37 | 38 | // $users = DB:: table('users') 39 | // -> orderBy('name', 'asc') 40 | // -> orderBy('age', 'desc') 41 | // -> get(); 42 | 43 | // Aggregating Records: 44 | // The count method allows you to retrieve the number of rows matching the query. 45 | 46 | 47 | // $count = DB:: table('users') 48 | // -> where('age', '>', 18) 49 | // -> count(); 50 | 51 | // Inserting Records: 52 | // The insert method is used to insert a new record into the database. 53 | 54 | 55 | // DB:: table('users') -> insert([ 56 | // ['name' => 'John Doe', 'email' => 'john@example.com'], 57 | // ['name' => 'Jane Smith', 'email' => 'jane@example.com'] 58 | // ]); 59 | 60 | // Updating Records: 61 | // The update method is used to update existing records in the database. 62 | 63 | 64 | // DB:: table('users') 65 | // -> where('id', 1) 66 | // -> update(['name' => 'New Name', 'email' => 'new@example.com']); 67 | 68 | // Deleting Records: 69 | // The delete method is used to delete records from the database. 70 | 71 | 72 | // DB:: table('users') 73 | // -> where('age', '<', 18) 74 | // -> delete (); 75 | 76 | 77 | // These are some of the commonly used query builder methods in Laravel.You can combine and chain these methods to construct complex queries.Remember to import the DB facade at the top of your file(use Illuminate\Support\Facades\DB;) to access the query builder. 78 | 79 | // Feel free to ask for further clarification or more specific examples! 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /understanding_laravel/relationship/1_one_to_one_relationship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/relationship/1_one_to_one_relationship.png -------------------------------------------------------------------------------- /understanding_laravel/relationship/2_one_to_many_relationship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/relationship/2_one_to_many_relationship.png -------------------------------------------------------------------------------- /understanding_laravel/relationship/3_many_to_many_relationship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/relationship/3_many_to_many_relationship.png -------------------------------------------------------------------------------- /understanding_laravel/relationship/4_polymorphic_relationship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/relationship/4_polymorphic_relationship.png -------------------------------------------------------------------------------- /understanding_laravel/relationship/5_define_relationship.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, you can define relationships between tables using Eloquent, which is Laravel's built-in ORM (Object-Relational Mapping) system. Eloquent provides a convenient and expressive way to interact with your database tables. 3 | 4 | There are four types of relationships you can define in Laravel: 5 | 6 | One-to-One Relationship: 7 | In a one-to-one relationship, each record in one table is associated with exactly one record in another table. To define a one-to-one relationship, you need to define the relationship methods in the corresponding Eloquent models and specify the foreign key and the local key. 8 | 9 | For example, let's say you have a "User" table and an "Address" table, where each user has only one address. You can define the one-to-one relationship in the "User" model like this: 10 | 11 | 12 | class User extends Model 13 | { 14 | public function address() 15 | { 16 | return $this->hasOne(Address::class); 17 | } 18 | } 19 | And in the "Address" model: 20 | 21 | 22 | class Address extends Model 23 | { 24 | public function user() 25 | { 26 | return $this->belongsTo(User::class); 27 | } 28 | } 29 | Here, we use the hasOne and belongsTo methods to define the relationship between the "User" and "Address" models. 30 | 31 | One-to-Many Relationship: 32 | In a one-to-many relationship, each record in one table can be associated with multiple records in another table. To define a one-to-many relationship, you also need to define the relationship methods in the models, but this time you specify the foreign key on the "many" side of the relationship. 33 | 34 | For example, let's consider a "Post" table and a "Comment" table, where each post can have multiple comments. You can define the one-to-many relationship like this: 35 | 36 | 37 | class Post extends Model 38 | { 39 | public function comments() 40 | { 41 | return $this->hasMany(Comment::class); 42 | } 43 | } 44 | And in the "Comment" model: 45 | 46 | 47 | class Comment extends Model 48 | { 49 | public function post() 50 | { 51 | return $this->belongsTo(Post::class); 52 | } 53 | } 54 | Here, we use the hasMany and belongsTo methods to define the relationship between the "Post" and "Comment" models. 55 | 56 | Many-to-Many Relationship: 57 | In a many-to-many relationship, each record in one table can be associated with multiple records in another table, and vice versa. To define a many-to-many relationship, you need to introduce a pivot table that holds the foreign keys of both tables involved. 58 | 59 | For example, let's say you have a "User" table and a "Role" table, where a user can have multiple roles, and a role can be associated with multiple users. You can define the many-to-many relationship like this: 60 | 61 | 62 | class User extends Model 63 | { 64 | public function roles() 65 | { 66 | return $this->belongsToMany(Role::class); 67 | } 68 | } 69 | And in the "Role" model: 70 | 71 | 72 | class Role extends Model 73 | { 74 | public function users() 75 | { 76 | return $this->belongsToMany(User::class); 77 | } 78 | } 79 | Here, we use the belongsToMany method to define the relationship between the "User" and "Role" models. 80 | 81 | Polymorphic Relationship: 82 | A polymorphic relationship allows a model to belong to more than one other model on a single association. This is useful when you have multiple models that can be associated with another model. 83 | 84 | For example, let's consider a scenario where you have a "Comment" model that can belong to either a "Post" model or a "Video" model. You can define the polymorphic relationship like this: 85 | 86 | 87 | class Comment extends Model 88 | { 89 | public function commentable() 90 | { 91 | return $this->morphTo(); 92 | } 93 | 94 | } 95 | And in the "Post" model: 96 | 97 | 98 | class Post extends Model 99 | { 100 | public function comments() 101 | { 102 | return $this->morphMany(Comment::class, 'commentable'); 103 | } 104 | } 105 | Similarly, in the "Video" model: 106 | 107 | 108 | class Video extends Model 109 | { 110 | public function comments() 111 | { 112 | return $this->morphMany(Comment::class, 'commentable'); 113 | } 114 | } 115 | Here, we use the morphTo method in the "Comment" model to indicate the polymorphic relationship, and the morphMany method in the "Post" and "Video" models to define the inverse of the relationship. 116 | 117 | These are the four primary types of relationships you can define between tables in Laravel using Eloquent. By correctly defining these relationships, you can easily query and retrieve related data between tables in a more convenient and intuitive manner. 118 | 119 | If you have any specific questions or need further assistance, feel free to ask! 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | */ -------------------------------------------------------------------------------- /understanding_laravel/relationship/6_foreignkey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/relationship/6_foreignkey.png -------------------------------------------------------------------------------- /understanding_laravel/relationship/8_one_to_many_relationship.js: -------------------------------------------------------------------------------- 1 | // 👉One - to - many relationships in Laravel. 2 | 3 | // In Laravel, you can define relationships between database tables using Eloquent, Laravel's ORM (Object-Relational Mapping) system. A one-to-many relationship is a common type of relationship where one record in a table is associated with multiple records in another table. 4 | 5 | // Let's say we have two tables: users and posts. Each user can have multiple posts, but a post belongs to only one user. We'll create a one - to - many relationship between these two tables. 6 | 7 | // First, let's set up the database tables. We'll assume you already have a Laravel project set up with a configured database connection. 8 | 9 | // ✅Create the users table migration: 10 | 11 | // php artisan make:migration create_users_table--create = users 12 | 13 | // This command will create a new migration file in the database / migrations directory. 14 | 15 | // Open the generated migration file and define the up and down methods as follows: 16 | 17 | 18 | // use Illuminate\Database\Migrations\Migration; 19 | // use Illuminate\Database\Schema\Blueprint; 20 | // use Illuminate\Support\Facades\Schema; 21 | 22 | // class CreateUsersTable extends Migration { 23 | // public function up() { 24 | // Schema:: create('users', function (Blueprint $table) { 25 | // $table -> id(); 26 | // // Add other columns as per your requirements 27 | // $table -> timestamps(); 28 | // }); 29 | // } 30 | 31 | // public function down() { 32 | // Schema:: dropIfExists('users'); 33 | // } 34 | // } 35 | 36 | // Create the posts table migration: 37 | 38 | //✅ php artisan make:migration create_posts_table--create = posts 39 | 40 | // Open the generated migration file and define the up and down methods as follows: 41 | 42 | 43 | // use Illuminate\Database\Migrations\Migration; 44 | // use Illuminate\Database\Schema\Blueprint; 45 | // use Illuminate\Support\Facades\Schema; 46 | 47 | // class CreatePostsTable extends Migration { 48 | // public function up() { 49 | // Schema:: create('posts', function (Blueprint $table) { 50 | // $table -> id(); 51 | // $table -> unsignedBigInteger('user_id'); // Foreign key column 52 | // $table -> string('title'); 53 | // $table -> text('content'); 54 | // $table -> timestamps(); 55 | 56 | // $table -> foreign('user_id') -> references('id') -> on('users'); 57 | // }); 58 | // } 59 | 60 | // public function down() { 61 | // Schema:: dropIfExists('posts'); 62 | // } 63 | // } 64 | 65 | // ✅Run the migrations to create the tables in the database: 66 | 67 | // php artisan migrate 68 | 69 | // Now that we have our database structure set up, let's define the Eloquent models and the relationship between them. 70 | 71 | // ✅Create the User model: 72 | 73 | // php artisan make:model User 74 | 75 | // ✅Open the generated User.php file located in the app / Models directory and define the relationship with Post model: 76 | 77 | 78 | // namespace App\Models; 79 | 80 | // use Illuminate\Database\Eloquent\Model; 81 | 82 | // class User extends Model { 83 | // public function posts() { 84 | // return $this -> hasMany(Post:: class); 85 | // } 86 | // } 87 | 88 | //✅ Create the Post model: 89 | 90 | // php artisan make:model Post 91 | 92 | //✅ Open the generated Post.php file located in the app / Models directory and define the relationship with User model: 93 | 94 | 95 | // namespace App\Models; 96 | 97 | // use Illuminate\Database\Eloquent\Model; 98 | 99 | // class Post extends Model { 100 | // public function user() { 101 | // return $this -> belongsTo(User:: class); 102 | // } 103 | // } 104 | 105 | // With the models and relationships set up, you can now use them to query and retrieve data. 106 | 107 | 108 | 109 | // ✅To retrieve the user associated with a post, you can use the belongsTo relationship defined in the Post model: 110 | 111 | 112 | // $post = Post:: find(1); 113 | // $user = $post -> user; 114 | // Now, let's look at some additional operations you can perform with one-to-many relationships: 115 | 116 | // ✅Creating a new post for a user: 117 | 118 | 119 | // $user = User:: find(1); 120 | // $post = new Post(); 121 | // $post -> title = "New Post Title"; 122 | // $post -> content = "New Post Content"; 123 | // $user -> posts() -> save($post); 124 | 125 | // In this example, we create a new Post instance, set its properties, and then use the save method on the user's posts relationship to save the post and associate it with the user. 126 | 127 | //✅ Updating a post for a user: 128 | 129 | 130 | // $user = User:: find(1); 131 | // $post = $user -> posts() -> find(1); 132 | // $post -> title = "Updated Post Title"; 133 | // $post -> content = "Updated Post Content"; 134 | // $post -> save(); 135 | 136 | // In this case, we retrieve a specific post belonging to a user and update its properties.Then, we call the save method to persist the changes to the database. 137 | 138 | // ✅Deleting a post for a user: 139 | 140 | 141 | // $user = User:: find(1); 142 | // $post = $user -> posts() -> find(1); 143 | // $post -> delete (); 144 | // Here, we find a specific post belonging to a user and call the delete method to remove it from the database. 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /understanding_laravel/request_response_lifecycle_in_laravel.js: -------------------------------------------------------------------------------- 1 | /* 2 | In Laravel, when a user makes a request to your application, Laravel processes that request and sends back a response. The request response lifecycle in Laravel can be broken down into several steps: 3 | 4 | The request is received by the web server: When a user makes a request to your Laravel application, the request is first received by the web server (such as Apache or Nginx). 5 | 6 | The request is directed to Laravel: The web server then directs the request to Laravel, which is responsible for processing the request. 7 | 8 | The request is routed: Laravel uses its routing system to determine which controller method should handle the request. The routing system maps the URI of the request to a specific controller method. 9 | 10 | The controller method is called: Once the routing system has determined which controller method should handle the request, Laravel calls that method. 11 | 12 | The controller method processes the request: The controller method processes the request, which may involve fetching data from a database, performing calculations, or any other actions necessary to fulfill the request. 13 | 14 | The response is generated: Once the controller method has finished processing the request, it generates a response. This response could be a view, a JSON response, or any other type of response. 15 | 16 | The response is sent back to the user: Finally, Laravel sends the response back to the user's browser, which displays the response to the user. 17 | 18 | Throughout this process, Laravel provides a number of hooks that developers can use to modify or extend the request response lifecycle. For example, middleware can be used to perform actions before or after the request is processed by the controller method. Event listeners can be used to respond to events that occur during the request response lifecycle, such as when a database query is executed. And view composers can be used to inject data into views before they are rendered. 19 | 20 | I hope this explanation helps you understand the request response lifecycle in Laravel! 21 | 22 | */ 23 | 24 | 25 | /* 26 | The request is received by the web server: 27 | When a user makes a request to your Laravel application, the request is first received by the web server. The web server listens for incoming requests on a specific port (usually port 80 for HTTP requests or port 443 for HTTPS requests) and sends the request to Laravel for processing. 28 | 29 | The request is directed to Laravel: 30 | The web server then directs the request to Laravel. This can be done using different server configurations such as Apache's mod_rewrite or Nginx's URL rewriting. Laravel routes incoming requests by matching the URI to the defined routes in the routes/web.php file. 31 | 32 | The request is routed: 33 | Once Laravel has received the request, it uses its routing system to determine which controller method should handle the request. The routing system maps the URI of the request to a specific controller method. The controller method is responsible for processing the request and returning a response. 34 | 35 | The controller method is called: 36 | Once the routing system has determined which controller method should handle the request, Laravel calls that method. The controller method is responsible for processing the request and returning a response. 37 | 38 | The controller method processes the request: 39 | The controller method processes the request, which may involve fetching data from a database, performing calculations, or any other actions necessary to fulfill the request. This is the main logic of your application and is where most of the work is done. 40 | 41 | The response is generated: 42 | Once the controller method has finished processing the request, it generates a response. This response could be a view, a JSON response, or any other type of response. Laravel provides several response types out-of-the-box, such as views, JSON responses, file downloads, and redirects. 43 | 44 | The response is sent back to the user: 45 | Finally, Laravel sends the response back to the user's browser, which displays the response to the user. The response is sent back to the user as HTTP response. The HTTP response includes a response code (such as 200 for success or 404 for not found) and any headers or content that should be sent back to the user's browser. 46 | 47 | Throughout the request response lifecycle, Laravel provides a number of hooks that developers can use to modify or extend the behavior of the application. For example, middleware can be used to perform actions before or after the request is processed by the controller method. Event listeners can be used to respond to events that occur during the request response lifecycle, such as when a database query is executed. And view composers can be used to inject data into views before they are rendered. 48 | 49 | I hope this explanation helps you understand the request response lifecycle in Laravel in more detail! 50 | 51 | */ -------------------------------------------------------------------------------- /understanding_laravel/routing_and_front_controller.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/routing_and_front_controller.png -------------------------------------------------------------------------------- /understanding_laravel/service_container/dependency_injection.js: -------------------------------------------------------------------------------- 1 | /* 2 | Dependency injection is a powerful concept in software development that allows you to manage the dependencies of your classes more effectively. In Laravel, the built-in service container provides a simple and intuitive way to implement dependency injection. 3 | 4 | Dependency injection helps you write code that is more modular, reusable, and testable by decoupling classes from their dependencies. It allows you to define the dependencies of a class from outside the class itself, making it easier to swap implementations and change the behavior of your code without modifying the class directly. 5 | 6 | To demonstrate dependency injection in Laravel, let's consider an example where we have a UserController class that requires an instance of the UserRepository class to retrieve user data from a database. Here's how you can achieve dependency injection: 7 | 8 | Define the interface for the UserRepository class: 9 | 10 | //app/Repositories/UserRepositoryInterface.php 11 | 12 | namespace App\Repositories; 13 | 14 | interface UserRepositoryInterface 15 | { 16 | public function getUsers(); 17 | } 18 | Implement the UserRepository class that implements the UserRepositoryInterface: 19 | 20 | // app/Repositories/UserRepository.php 21 | 22 | namespace App\Repositories; 23 | 24 | class UserRepository implements UserRepositoryInterface 25 | { 26 | public function getUsers() 27 | { 28 | // Code to fetch users from the database 29 | } 30 | } 31 | Bind the interface to its implementation in Laravel's service container. You can do this in the AppServiceProvider class or create a new service provider: 32 | php 33 | Copy code 34 | // app/Providers/AppServiceProvider.php 35 | 36 | namespace App\Providers; 37 | 38 | use App\Repositories\UserRepository; 39 | use App\Repositories\UserRepositoryInterface; 40 | use Illuminate\Support\ServiceProvider; 41 | 42 | class AppServiceProvider extends ServiceProvider 43 | { 44 | public function register() 45 | { 46 | $this->app->bind(UserRepositoryInterface::class, UserRepository::class); 47 | } 48 | } 49 | Now, you can inject the UserRepositoryInterface into the UserController constructor: 50 | php 51 | Copy code 52 | // app/Http/Controllers/UserController.php 53 | 54 | namespace App\Http\Controllers; 55 | 56 | use App\Repositories\UserRepositoryInterface; 57 | 58 | class UserController extends Controller 59 | { 60 | protected $userRepository; 61 | 62 | public function __construct(UserRepositoryInterface $userRepository) 63 | { 64 | $this->userRepository = $userRepository; 65 | } 66 | 67 | public function index() 68 | { 69 | $users = $this->userRepository->getUsers(); 70 | 71 | // Code to handle and return users 72 | } 73 | } 74 | By using dependency injection, Laravel's service container will automatically resolve the UserRepositoryInterface dependency when creating an instance of the UserController class. This allows you to swap different implementations of the UserRepositoryInterface in a clean and modular way. 75 | 76 | Remember to make sure that your service provider is registered in the config/app.php file under the providers array. 77 | 78 | I hope this explanation helps you understand dependency injection in Laravel. Let me know if you have any further questions! 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/dependency_inversion_principle.js: -------------------------------------------------------------------------------- 1 | /* 2 | Program to an Interface principle (also known as the Dependency Inversion Principle) in Laravel. 3 | 4 | The Program to an Interface principle promotes writing code that depends on interfaces rather than concrete implementations. It encourages loose coupling between classes and allows for easier substitution of implementations. Laravel provides a convenient way to apply this principle through its service container and the use of interface bindings. 5 | 6 | Let's walk through an example to understand how to program to an interface in Laravel: 7 | 8 | Create an interface that defines the contract for the desired functionality. For instance, let's say we want to create a PaymentGateway to process payments: 9 | 10 | namespace App\Contracts; 11 | 12 | interface PaymentGateway 13 | { 14 | public function processPayment(float $amount): bool; 15 | } 16 | Implement the PaymentGateway interface with concrete classes that provide the payment processing logic. Here's an example implementation using a StripePaymentGateway: 17 | 18 | namespace App\Services; 19 | 20 | use App\Contracts\PaymentGateway; 21 | 22 | class StripePaymentGateway implements PaymentGateway 23 | { 24 | public function processPayment(float $amount): bool 25 | { 26 | // Code to process payment using the Stripe API 27 | 28 | return true; // Payment successful 29 | } 30 | } 31 | Bind the interface to its implementation in the Laravel service container. This allows Laravel to automatically resolve the dependency when requested: 32 | php 33 | Copy code 34 | $this->app->bind(PaymentGateway::class, StripePaymentGateway::class); 35 | Now, in your controller or any other class where you need to use the payment gateway, you can depend on the interface rather than the concrete implementation: 36 | 37 | namespace App\Http\Controllers; 38 | 39 | use App\Contracts\PaymentGateway; 40 | 41 | class PaymentController extends Controller 42 | { 43 | protected $paymentGateway; 44 | 45 | public function __construct(PaymentGateway $paymentGateway) 46 | { 47 | $this->paymentGateway = $paymentGateway; 48 | } 49 | 50 | public function processPayment(float $amount) 51 | { 52 | $result = $this->paymentGateway->processPayment($amount); 53 | 54 | if ($result) { 55 | // Payment successful logic 56 | } else { 57 | // Payment failure logic 58 | } 59 | } 60 | } 61 | By depending on the PaymentGateway interface rather than the concrete implementation (StripePaymentGateway), the PaymentController is following the Program to an Interface principle. It can work with any implementation of PaymentGateway, providing flexibility and making it easier to switch payment gateways if needed. 62 | 63 | This approach promotes decoupling, maintainability, and testability in your codebase. It also allows you to easily mock dependencies during testing. 64 | 65 | Remember to register the interface and its implementation in a service provider's register method, as mentioned in the binding step. 66 | 67 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/inversion_of_control_principle.js: -------------------------------------------------------------------------------- 1 | /* 2 | Inversion of Control (IoC) is a design principle that aims to decouple the dependencies between classes by inverting the control of object creation and dependency resolution. In traditional programming, a class often creates its own dependencies, leading to tight coupling and decreased flexibility. With IoC, the responsibility of creating and managing dependencies is shifted to an external entity, typically a container or framework. 3 | 4 | Laravel implements IoC through its service container, which is responsible for resolving and injecting dependencies. Here's an example to illustrate how IoC works in Laravel: 5 | 6 | Consider a UserController class that depends on a UserRepository interface for database operations: 7 | 8 | namespace App\Http\Controllers; 9 | 10 | use App\Repositories\UserRepository; 11 | 12 | class UserController extends Controller 13 | { 14 | protected $userRepository; 15 | 16 | public function __construct(UserRepository $userRepository) 17 | { 18 | $this->userRepository = $userRepository; 19 | } 20 | 21 | // Controller methods... 22 | } 23 | Instead of directly instantiating the UserRepository inside the UserController, we rely on Laravel's service container to resolve the dependency. This is achieved through constructor injection, where the UserRepository is automatically resolved and injected into the UserController constructor. 24 | 25 | Laravel's service container analyzes the type-hinted constructor parameter (UserRepository) and resolves it by searching for a binding or registered implementation. 26 | 27 | To bind the UserRepository interface to its concrete implementation, you can define it in a service provider's register method: 28 | 29 | 30 | namespace App\Providers; 31 | 32 | use App\Repositories\UserRepository; 33 | use App\Repositories\UserRepositoryInterface; 34 | use Illuminate\Support\ServiceProvider; 35 | 36 | class AppServiceProvider extends ServiceProvider 37 | { 38 | public function register() 39 | { 40 | $this->app->bind(UserRepositoryInterface::class, UserRepository::class); 41 | } 42 | } 43 | In this example, we use the bind method to register the UserRepository implementation to the UserRepositoryInterface contract. 44 | 45 | Laravel's service container will now automatically resolve the UserRepository whenever it encounters a dependency on UserRepositoryInterface. It will create a new instance of the UserRepository and inject it into the UserController constructor. 46 | By using IoC in Laravel, we achieve loose coupling between classes, making our code more flexible and maintainable. It also enables us to easily swap implementations and mock dependencies during testing. 47 | 48 | The service container in Laravel is an essential component that implements the IoC principle, allowing you to take advantage of dependency injection and write modular, extensible, and testable code. 49 | 50 | If you have any further questions or need more clarification, feel free to ask! 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/ioc_container.js: -------------------------------------------------------------------------------- 1 | /* 2 | The IoC container in Laravel is a powerful feature that manages the instantiation and resolution of dependencies for your application. It allows you to implement dependency injection easily and follow the principle of Inversion of Control. 3 | 4 | Here's how you can work with the IoC container in Laravel: 5 | 6 | Binding Dependencies: 7 | 8 | The bind method is used to register a binding in the container. It associates an abstract interface or key with a concrete implementation or value. 9 | The singleton method is used to bind a concrete implementation as a shared instance, meaning the same instance will be returned whenever the binding is resolved. 10 | Here's an example of binding an interface to a concrete implementation in a service provider: 11 | 12 | $this->app->bind(Interface::class, Concrete::class); 13 | Resolving Dependencies: 14 | 15 | Laravel's IoC container automatically resolves dependencies when a class or interface is requested. 16 | Constructor injection is the default method used by the container to resolve dependencies. It analyzes the type-hinted constructor parameters and automatically resolves them. 17 | Here's an example of resolving a dependency from the container: 18 | 19 | $dependency = app(Interface::class); 20 | Contextual Binding: 21 | 22 | Laravel allows you to bind different implementations based on a context or condition using the when method. 23 | You can specify contextual bindings based on parameter values or conditions in the current application state. 24 | Here's an example of contextual binding in a service provider: 25 | 26 | $this->app->when(ClassA::class) 27 | ->needs(Interface::class) 28 | ->give(ConcreteA::class); 29 | Resolving Dependencies in Controllers: 30 | 31 | Laravel's IoC container is automatically used to resolve dependencies in your controllers. 32 | Simply type-hint the dependencies in your controller's constructor, and Laravel will resolve them for you. 33 | Here's an example of a controller with dependencies: 34 | 35 | namespace App\Http\Controllers; 36 | 37 | use App\Contracts\Interface; 38 | 39 | class ExampleController extends Controller 40 | { 41 | protected $dependency; 42 | 43 | public function __construct(Interface $dependency) 44 | { 45 | $this->dependency = $dependency; 46 | } 47 | 48 | // Controller methods... 49 | } 50 | Resolving Dependencies in Methods: 51 | 52 | Apart from constructor injection, you can also resolve dependencies in methods using the IoC container. 53 | Use method injection by type-hinting the desired dependency in the method's parameter list. 54 | Here's an example of a method with a resolved dependency: 55 | 56 | public function exampleMethod(Interface $dependency) 57 | { 58 | // Use the resolved dependency 59 | } 60 | The Laravel IoC container is a powerful tool that simplifies dependency management and promotes decoupling between classes. It allows you to program to interfaces, swap implementations easily, and write testable code. 61 | 62 | Remember to register your bindings in a service provider's register method and ensure that the provider is registered in the config/app.php configuration file. 63 | 64 | I hope this explanation and the provided examples help you understand the Laravel IoC container. Feel free to ask if you have any further questions! 65 | 66 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/reflection.js: -------------------------------------------------------------------------------- 1 | /* 2 | Reflection is a powerful feature in PHP that allows you to inspect and manipulate classes, interfaces, methods, properties, and more at runtime. Laravel leverages reflection to provide dynamic capabilities, such as dependency injection, method invocation, and class introspection. 3 | 4 | Here are some examples of using reflection in Laravel: 5 | 6 | Getting Class Information: 7 | 8 | You can use reflection to obtain information about a class, such as its methods, properties, and inheritance hierarchy. 9 | Here's an example that retrieves the methods of a class: 10 | 11 | $reflectionClass = new ReflectionClass(ClassName::class); 12 | $methods = $reflectionClass->getMethods(); 13 | Dependency Injection with Reflection: 14 | 15 | Laravel's IoC container uses reflection to resolve and inject dependencies automatically. 16 | Here's an example of constructor injection with reflection in Laravel: 17 | 18 | $reflectionClass = new ReflectionClass(ExampleClass::class); 19 | $constructor = $reflectionClass->getConstructor(); 20 | $dependencies = $constructor->getParameters(); 21 | 22 | $resolvedDependencies = []; 23 | foreach ($dependencies as $dependency) { 24 | $dependencyClass = $dependency->getClass(); 25 | $resolvedDependency = app($dependencyClass->getName()); 26 | $resolvedDependencies[] = $resolvedDependency; 27 | } 28 | 29 | $exampleInstance = $reflectionClass->newInstanceArgs($resolvedDependencies); 30 | Method Invocation with Reflection: 31 | 32 | Reflection allows you to invoke methods dynamically by name. 33 | Here's an example that invokes a method on an object using reflection: 34 | 35 | $reflectionMethod = new ReflectionMethod($object, 'methodName'); 36 | $reflectionMethod->invoke($object, $arg1, $arg2); 37 | Dynamic Property Access with Reflection: 38 | 39 | Reflection enables you to get or set the value of a class's property dynamically. 40 | Here's an example that gets the value of a property using reflection: 41 | 42 | $reflectionProperty = new ReflectionProperty($object, 'propertyName'); 43 | $reflectionProperty->setAccessible(true); 44 | $propertyValue = $reflectionProperty->getValue($object); 45 | These are just a few examples of how reflection can be used in Laravel. Reflection provides a powerful way to work with classes and objects dynamically at runtime, making it possible to build flexible and extensible applications. 46 | 47 | Remember to include the appropriate use statements for the Reflection classes you need to use in your code. 48 | 49 | 50 | 51 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/service_container.js: -------------------------------------------------------------------------------- 1 | /* 2 | The service container is a powerful feature provided by Laravel that serves as a central hub for managing and resolving dependencies throughout your application. 3 | 4 | The service container in Laravel acts as a IoC (Inversion of Control) container, responsible for creating and managing instances of your classes, resolving dependencies, and providing them when needed. It helps decouple your code and makes it easier to swap implementations, achieve dependency injection, and manage the lifecycle of objects. 5 | 6 | Here are the key aspects of the service container in Laravel: 7 | 8 | Binding: 9 | 10 | The bind method allows you to register a binding in the service container. It associates an abstract interface or key with a concrete implementation or value. 11 | The singleton method is used to bind a concrete implementation as a shared instance, meaning the same instance will be returned whenever the binding is resolved. 12 | Resolving Dependencies: 13 | 14 | When a class or interface is requested from the service container, it automatically resolves its dependencies recursively. 15 | Constructor injection is the default method used by the service container to resolve dependencies. It analyzes the type-hinted constructor parameters and automatically resolves them. 16 | You can also use method injection or property injection to resolve dependencies. 17 | 18 | Contextual Binding: 19 | 20 | Laravel allows you to bind different implementations based on the context or condition. This is achieved using the when method. 21 | You can specify contextual bindings based on the values of parameters or conditions in the current application state. 22 | 23 | Automatic Resolution: 24 | 25 | Laravel's service container can automatically resolve many types of dependencies, including primitive types, classes, interfaces, and even dependencies with complex hierarchies. 26 | 27 | For example, if you have an ExampleClass that requires an instance of DependencyClass in its constructor, you can simply type-hint the dependency, and Laravel will automatically resolve it. 28 | 29 | Service Provider: 30 | 31 | Service providers are used to bootstrap and register services in the service container. 32 | They provide a way to organize and encapsulate related bindings and configurations. 33 | Service providers define the register method, where you can bind classes and interfaces, and the boot method, where you can perform additional setup tasks. 34 | 35 | The service container in Laravel is at the core of dependency injection and allows you to write clean, modular, and testable code. It enables you to manage and resolve dependencies efficiently throughout your application. 36 | 37 | If you have any specific questions about the service container or need further clarification, feel free to ask! 38 | */ -------------------------------------------------------------------------------- /understanding_laravel/service_container/service_provider.js: -------------------------------------------------------------------------------- 1 | /* 2 | Service providers play a crucial role in bootstrapping and configuring various components of your Laravel application. They allow you to register bindings, provide configuration options, and perform other setup tasks. 3 | 4 | A service provider acts as a central location to configure and register services, allowing you to organize your application's initialization code in a modular and extensible way. Laravel provides a base ServiceProvider class that you can extend to create your own custom service providers. 5 | 6 | Let's walk through the steps to create and use a service provider in Laravel: 7 | 8 | Create a new service provider using the artisan command: 9 | 10 | php artisan make:provider MyServiceProvider 11 | This command generates a new file MyServiceProvider.php in the app/Providers directory. 12 | 13 | Open the MyServiceProvider class and implement the necessary methods. The register method is where you can bind interfaces to their implementations in the Laravel service container. The boot method is used for any bootstrapping or additional setup tasks. 14 | 15 | namespace App\Providers; 16 | 17 | use Illuminate\Support\ServiceProvider; 18 | 19 | class MyServiceProvider extends ServiceProvider 20 | { 21 | public function register() 22 | { 23 | $this->app->bind(MyInterface::class, MyImplementation::class); 24 | } 25 | 26 | public function boot() 27 | { 28 | // Additional setup or bootstrapping tasks 29 | } 30 | } 31 | Register your service provider in the config/app.php configuration file. Add it to the providers array: 32 | 33 | 'providers' => [ 34 | // Other service providers... 35 | App\Providers\MyServiceProvider::class, 36 | ], 37 | Once your service provider is registered, you can start using the bindings in your application. For example, if you have an ExampleController that requires an instance of MyInterface, you can inject it into the controller's constructor: 38 | 39 | namespace App\Http\Controllers; 40 | 41 | use App\Interfaces\MyInterface; 42 | 43 | class ExampleController extends Controller 44 | { 45 | protected $myInstance; 46 | 47 | public function __construct(MyInterface $myInstance) 48 | { 49 | $this->myInstance = $myInstance; 50 | } 51 | 52 | // Rest of the controller's code... 53 | } 54 | You can also use the artisan command to view a list of registered service providers in your application: 55 | bash 56 | Copy code 57 | php artisan route:list 58 | This command will display a table that includes the service providers along with other information. 59 | 60 | That's it! Your service provider is now set up and ready to use. It allows you to register bindings, resolve dependencies, and perform any additional setup tasks your application may require. 61 | 62 | Remember that service providers are essential components in the Laravel framework, and they enable you to keep your code organized, modular, and easy to maintain. 63 | 64 | If you have any further questions, feel free to ask! 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | */ -------------------------------------------------------------------------------- /understanding_laravel/templating.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/templating.png -------------------------------------------------------------------------------- /understanding_laravel/understanding laravel concepts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/understanding laravel concepts.png -------------------------------------------------------------------------------- /understanding_laravel/understanding_factory_seeder/factory.js: -------------------------------------------------------------------------------- 1 | /* 2 | Model factories are mostly used for testing purposes because it allows 3 | you to generate a huge amount of fake data. 4 | 5 | Seeder classes are used to insert data that is important for the system to operate with. 6 | 7 | 8 | */ -------------------------------------------------------------------------------- /understanding_laravel/understanding_migration/note_for_migration.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1. php artisan make:migration create_posts_table 3 | 2. php artisan migrate 4 | 3. php artisan migrate:status 5 | 4. php artisan migrate --pretend // we should run it before migrate 6 | 5. php artisan migrate:reset //rollback all the database migrations and reset the database to its initial state. 7 | 6. php artisan migrate --force //This command will execute the migrations without any confirmation prompt, allowing the migrations to run in a production environment. 8 | 9 | 7. php artisan migrate:rollback 10 | 8. php artisan migrate:rollback --step=2 11 | 9. php artisan migrate:refresh //refresh the database by rolling back all migrations and then re-running them. It effectively resets the database to its initial state and re-applies all migrations. 12 | 10.php artisan migrate:refresh --step=2 13 | 14 | 11. php artisan migrate:fresh //This command will drop all tables from the database and then re-run all migrations using the migrate command. It effectively resets the database and applies all migrations from the beginning. 15 | 16 | 12. php artisan make:migration add_soft_deletes_in_posts_table --table=posts 17 | 18 | 13. php artisan make:migration rename_description_to_content_on_posts_table --table=posts 19 | 14. composer require doctrine/dbal //for renaming we need to install this package 20 | 15. php artisan make:migration drop_deleted_at_from_posts_table --table=posts 21 | 22 | */ 23 | -------------------------------------------------------------------------------- /understanding_laravel/who_is_better_developer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/laravel_basic/7462935c11c30757f2fa0d0ebc07a41983d63853/understanding_laravel/who_is_better_developer.png --------------------------------------------------------------------------------