Learn Laravel Category, A Comparison Between Laravel And Phalcon

In this Laravel tutorial, we will learn how khổng lồ install laravel và how to lớn create your first ứng dụng in laravel for beginners. Now you can learn laravel easily without the need of watching laravel clip series or laravel đoạn clip tutorials. This laravel tutorial will explain all the necessary concepts in easy language for you lớn learn laravel easily and understand it better.Bạn đang xem: Menu

Introduction

Laravel is elegant, expressive and flexible PHP framework with extreme focus on clean code và speed which describes itself as “The PHP framework for web artisans”. It is a không lấy phí and xuất hiện source PHP framework created by Taylor Otwell, based on mã sản phẩm View Controller (MVC) architecture.

Bạn đang xem: Learn laravel category, a comparison between laravel and phalcon

Creating a web application from scratch can be daunting specially if you are beginner. A simple web application also contains various small and big pieces và creating those pieces every time you are creating a web phầm mềm can be boring và repetitive & there is no point in reinventing wheels. That’s when Laravel comes to your rescue.


*

Laravel framework provides various PHP libraries and helper functions and can help you to focus on more important pieces while providing common functions and lô ghích to tốc độ up the development time & ease up the development.

Initially there is a bit of learning curve specially if you are a beginner and have no experience with any kind of website framework. But believe me, once you flow with it, you will not only love, you will become addicted khổng lồ it. Laravel aims at creativity in development. It uses the word ‘Web Artisan’ lớn point out the creative hidden inside the developer’s heart.Result -> Efficient Application with fewer lines & well designed code.

To make it easier for you to learn, I wrote this laravel tutorial with beginner audience in mind. Thus you will find it easy to lớn follow this tutorial for laravel khổng lồ learn.

What you should know prior khổng lồ using our Laravel tutorial?

HTML/CSS (Duh!)Basic understanding of core PHPBasic Understanding of MVC FrameworkPerseverance – Even though it’s easy khổng lồ learn Laravel, it will kiểm tra your patience at various interval. At least I had some roadblocks because I knew PHP but I had no knowledge about frameworks. Even while learning the framework, or successfully completing projects, I was having confusion in the basic underlying concepts of the MVC Framework. But I didn’t give up.Passion – C’mon web development is fun! At least Laravel made it enjoyable. It’s best khổng lồ enjoy the learning journey.

Installation & Configuration

Laravel offers various ways to lớn install in windows or mac. Best and easiest way to lớn install Laravel is through Composer. Composer is dependency manager for PHP which you can install on your web server.

Prerequisites for installing Laravel 8

Before installing Laravel on your local platform (Localhost) you need to lớn install following programs:

Make sure brew is installed.

Install Composer using below command (If you had composer already installed & setup, ignore this) :

Now, install Laravel Installer using below command:Now execute below command khổng lồ place Composer/vendor/bin directory to $PATH variable (If you had composer already installed & setup, ignore this) Once installed, you can create project simply byGoing lớn desired folderExecute - laravel new projectnameSteps for Windows users (Click Here)

Place ~/.composer/vendor/bin directory path in your environment variable PATH

Now execute this command –

Once installed, you can create project simply byGoing lớn desired folderShift + right click & select Open command prompt hereExecute -- laravel new projectname

For our example , execute

Building Simple CRUD To-do Application in Laravel : Laravel Tutorial

Best way to learn programming is to lớn practice. Thus, here we will be learning basic concepts of Laravel by developing a simple To-Do Laravel Web phầm mềm which will vì chưng below functions with the help of this laravel tutorial.You can register và login to lớn the website appYou can add tasks khổng lồ your to-do listYou can edit as well as delete those tasksYour list is only visible to lớn you thus it implements authentication using email id và password

Exploring Directory Structure

Laravel applications follow the Model-View-Controller architecture design pattern.


*

Source - SelfTaughtCoders.com

Models represents the entities in database và helps you lớn query the database & return the dataViews are the pages which will be displayed when accessed the app. View Component is used for the User Interface of the application.Controllers handle user requests, gets required data from the models và pass them to the Views. Controllers acts as an intermediary between mã sản phẩm and View Components to process the business ngắn gọn xúc tích and incoming request.

When you installed composer, và created your first Laravel web app, you might have noticed the app thư mục with different files & folders. I know if you are beginner, you may have a lot of questions about what are these folders for etc. Etc.

Let’s understand some

app Console Exceptions Http Models Providersbootstrapconfigdatabase migrations seedspublicresources css js lang viewsroutesstorage app framework logstestsvendorApp: This directory is the meat of the application và contains the bộ vi xử lý core code.Console: This directory contains all the custom Artisan commands created using make:commandExceptions: This directory contains the application’s exception handler and is a good place to địa chỉ custom exception classes lớn handle different exceptions thrown by your applicationHttp: This directory contains all your controllers, middleware và requestsModels This is a new director added since Laravel 8 to hold model files. Earlier, models were stored at app folder, but now it can be stored inside App/Models folders too.Bootstrap: This directory contains framework bootstrap as well as configuration files. It also contains Cache directory which contains framework generated cache filesConfig: This directory contains all your application’s configuration files.Database: This directory contains all database migrations và seeds. You can also store SQLite database file herePublic: This directory contains assets like images, js files và CSS.Resources: This directory contains all view files & CSS or LESS or SASS files. It also contains lang directory to store language files.Routes: This directory contains all routes definitions for the application. php is the file which receives all the requests to lớn your application & here you can redirect the requests to their respective controller methods.Storage: This directory contains blade templates, session files, cache files và other.Tests: This directory contains all the test filesVendor: This directory contains all composer dependencies

Steps to lớn create your first Laravel Application using Laravel tutorial

1) Create Your Project:If you didn’t create your project in installation section, create now by executing below command:

2) Configure Database:We need database for our application, so it’s best khổng lồ configure our database before doing anything. Laravel supports following 4 databases −MySQLPostgresSQLiteSQL Server

For this example, we will use SQLite as it is easy khổng lồ configure and to use và you don’t have lớn install anything apart from creating just one empty file.

For other databases, you need khổng lồ have that database installed in your system and then you can configure accordingly.

Laravel provides config/database.php lớn config database but it's better not to store database credentials there instead you can use .env tệp tin where you can different types of credentials và other data.

Laravel comes with mặc định .env tệp tin at root.

3) Make Auth:

Laravel also provides Authentication Scaffolding which means everything related to lớn Authentication like User login, registration, forget password, two-factor authentication etc will be pre-built if you need và it is called Laravel Jetstream

There is two ways to địa chỉ cửa hàng Jetstream to your new Laravel App. If you haven't created laravel project yet, add

--jet

flag to lớn laravel new command like this:

Since, we already created project above, you can also install it via their package. First install jetstream packing using below command:Laravel Jetstream supports two stack ~ Liveware or Inerta. Since, we want to lớn keep this project simple, let's use Livewire and install jetstream using below command:
*

Then run "npm install && npm run dev" khổng lồ build your assets.

At this point - all the configuration are done and we are ready to start building.

4) Migrations:

First step in developing any website application is to lớn design database. Laravel offers great way khổng lồ design database schema and tables & able to lớn migrate it easily over different systems known as 'Migrations'.

Xem thêm: các món tôm dễ làm

Migrations are used khổng lồ create, modify as well as cốt truyện the application’s database schema. They are used with Laravel’s schema builder to lớn build database schema easily. There are many benefits lớn create migrations for your database. You can easily rebuild your database structure using migration files on production or any other system.

Don’t worry if you find this explanation confusing. Believe me, you will get your way soon. Just follow along.

Execute below command:

You will find your newly created migration in /database/migrations thư mục –


*

...public function up() Schema::create('tasks', function (Blueprint $table) $table->bigIncrements('id'); $table->string('description'); $table->integer('user_id')->unsigned()->index(); $table->timestamps(); );...The new column named “description” will store the task description & column named “user_id” will store the id of the user who created the task. We added “ ->unsigned()->index()” after the user_if because it is a foreign key from users table.

Now We finished creating the database schema. To lớn use this schema to create tables in the database, execute below command. Migrate command will update the changes made in schema to lớn the actual database.

5) Eloquent ModelsEloquent is Laravel’s ORM which provides simple Active-record Implementation for working with database. Each Database table can have corresponding Eloquent model. Eloquent mã sản phẩm represents database entities và can be used lớn query data as well as insert & update data lớn the tables. So, let’s make a model for our tasks table using make:model command.This command will create Task model in ứng dụng directory as shown below.


*

6) One-to-Many Relationship

Relationships are used lớn connect tables. Eloquent provides way to connect their models through eloquent relationships. One-to-many relationship means when one mã sản phẩm owns multiple amounts of another model.For our example: single user can have many tasks thus one-to-many relationship exists between User table và Task Table. It's very easy lớn define và use Eloquent relationship và the benefit is, you don’t have to run query at all. Eloquent will bind the models so you will have to only use functions.

Let’s edit Task mã sản phẩm and User mã sản phẩm to create Eloquent Relationship:

Task model (task.php found in app/task.php):

...use AppModelsUser;class Task extends Model public function user() return $this->belongsTo(User::class); ...use AppModelsTask;class User extends Authenticatable ... Public function tasks() return $this->hasMany(Task::class); 7) Artisan Tinker - (Totally Optional)Laravel provides a command-line interface known as Artisan. Artisan contains various commands và among them, we will now discuss about Tinker. Tinker allows you to lớn interact with your entire Laravel application through console window without the need of accessing web interface. Major benefit of tinker is you can test relationships, debug data và access Eloquent ORM, jobs, tests, events etc. So we will also be using Tinker in our laravel tutorial. Let’s say you registered to lớn the app & created two tasks. Now you kiểm tra those tasks directly in the console window as below:

Tinker directly access database so this is a great tool for testing functions as well as the data.8) Controllers

Controllers are used lớn direct traffic between views và models và they can group multiple request handling xúc tích và ngắn gọn into a single class. Thus, generally they receive all the request and based on their logic, they redirect or return respective data. In our example, now we are moving towards front-end, thus we should make controllers through which we can handle requests coming khổng lồ our application. Execute below command to create controller for tasks:

This will create TasksController and you can find that in app/Http/Controllers directory.9) Routing

Routing means to accept the request & redirect it to lớn appropriate function. Our phầm mềm needs five routes which will bởi following:

LoginRegisterDisplay các mục of all our tasksAdd new tasksDelete existing tasks

Login & register are added by Laravel Jetstream so now we need to take care of only three routes.

Laravel provides various route files inside '/routes' thư mục for various use cases. For example: routing configuration for API will go in '/routes/api.php' tệp tin while routing configuration for our regular web application will go in '/routes/web.php'.

Now, let’s edit web.php. Below is the edited version of file. Make changes accordingly:

use IlluminateSupportFacadesRoute;use AppHttpControllersTasksController;/*|--------------------------------------------------------------------------| web Routes|--------------------------------------------------------------------------|| Here is where you can register website routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/Route::get('/', function () return view('welcome'););Route::middleware()->group(function() Route::get('/dashboard',)->name('dashboard'); Route::get('/task',); Route::post('/task',); Route::get('/task/task', ); Route::post('/task/task', ););Here, we have done two changes:

We have grouped all routes so we can apply auth:sanctum & verified middleware khổng lồ all routes thereby restricting those pages to lớn only verified, logged in users.We have modified route for dashboard, which will now pass request khổng lồ TaskController's Index function. And created routes for other actions.10) Views – Blade Templates

Views are stored in resources/views directory. Views are the front-end of the Laravel application & it separates application logic and the presentation logic. We need to create và design following views:

dashboard.blade.php ( Dashboard will show list of tasks)add.blade.php (Form which lets you to địa chỉ cửa hàng new task)edit.blade.php (Form which lets you lớn edit any task)

Laravel comes with decent layout which contains navbar called app.blade.php located in Views/layouts directory.

With the help of laravel’s blade engine, you can divide your pages into sub-sections & also can use the laravel’s default navbar section into your new views.

Now, in /resources/views folder, create add.blade.php and edit.blade.php files with the markup given below.

x-app-layout> x-slot name="header"> h2 class="font-semibold text-xl text-gray-800 leading-tight"> //here goes your page header /h2> /x-slot>//here goes your body toàn thân content/x-app-layout>In dashboard.blade.php too, replace all code with the above. We will edit the views later after defining our controller functions using Route-Model Binding concept.

11) Route-Model Bindng

Laravel has lot of amazing features khổng lồ make web development easy, clean, & less time consuming. Among them, one of the most prominent feature is Route-Model Binding. It is a mechanism khổng lồ inject a mã sản phẩm instance into your routes. It means, you can pass the mã sản phẩm object to lớn the routes và also khổng lồ views through routes which will help you to get the object values easily in the view.Don’t worry if explanation is confusing. With time, you will get to lớn know.

Now let’s địa chỉ cửa hàng functions handling above routes to lớn TasksController.php. It should look like below.

namespace AppHttpControllers;use IlluminateHttpRequest;use AppModelsTask;class TasksController extends Controller public function index() $tasks = auth()->user()->tasks(); return view('dashboard', compact('tasks')); public function add() return view('add'); public function create(Request $request) $this->validate($request, 'required' >); $task = new Task(); $task->description = $request->description; $task->user_id = auth()->user()->id; $task->save(); return redirect('/dashboard'); public function edit(Task $task) if (auth()->user()->id == $task->user_id) return view('edit', compact('task')); else return redirect('/dashboard'); public function update(Request $request, Task $task) if(isset($_POST)) $task->delete(); return redirect('/dashboard'); else $this->validate($request, 'required' >); $task->description = $request->description; $task->save(); return redirect('/dashboard'); Here you can see that I am passing “Task $task” object in the function as well as “Request $request” object with the help of Route-model binding mechanism.

Note: Don't forget to showroom 'use AppModelsTask;' otherwise you will get 'Class not found error'

12) Editing views

Now we have our controller functions set up và returning the appropriate views with the attached mã sản phẩm objects.So now, we need to lớn edit our views so that it displays the size if necessary và needed data using mã sản phẩm objects passed through routes.

Display all tasks page

Open dashboard.blade.php và edit it to the following.

x-app-layout>x-slot name="header"> h2 class="font-semibold text-xl text-gray-800 leading-tight"> __('Dashboard') /h2>/x-slot>div class="py-12"> div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-5"> div class="flex"> div class="flex-auto text-2xl mb-4">Tasks List/div> div class="flex-auto text-right mt-2"> a href="/task" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Add new Task/a> /div> /div> table class="w-full text-md rounded mb-4"> thead> tr class="border-b"> th class="text-left p-3 px-5">Task/th> th class="text-left p-3 px-5">Actions/th> th>/th> /tr> /thead> tbody> foreach(auth()->user()->tasks as $task) tr class="border-b hover:bg-orange-100"> td class="p-3 px-5"> $task->description /td> td class="p-3 px-5"> a href="/task/$task->id" name="edit" class="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Edit/a> form action="/task/$task->id" class="inline-block"> button type="submit" name="delete" formmethod="POST" class="text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Delete/button> csrf_field() /form> /td> /tr> Tip:

Blade template engine allows us khổng lồ use php inside HTML without enclosing it inside “”.

Add new task page

Open add.blade.php & edit as following:

x-app-layout>x-slot name="header"> h2 class="font-semibold text-xl text-gray-800 leading-tight"> __('Add Task') /h2>/x-slot>div class="py-12"> div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-5"> khung method="POST" action="/task"> div class="form-group"> textarea name="description" class="bg-gray-100 rounded border border-gray-400 leading-normal resize-none w-full h-20 py-2 px-3 font-medium placeholder-gray-700 focus:outline-none focus:bg-white" placeholder='Enter your task'>/textarea> if ($errors->has('description')) span class="text-danger"> $errors->first('description') /span> endif /div> div class="form-group"> button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Add Task/button> /div> csrf_field() /form> /div> /div>/div>/x-app-layout>Tip:

csrf_field() is used to lớn generate csrf token & insert in the form. This token is used lớn verify that the authenticated logged user is the one making request in application. This is the security feature provided by Laravel out of the box.

Edit task page

Open edit.blade.php and edit as following.

x-app-layout>x-slot name="header"> h2 class="font-semibold text-xl text-gray-800 leading-tight"> __('Edit Task') /h2>/x-slot>div class="py-12"> div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-5"> size method="POST" action="/task/ $task->id "> div class="form-group"> textarea name="description" class="bg-gray-100 rounded border border-gray-400 leading-normal resize-none w-full h-20 py-2 px-3 font-medium placeholder-gray-700 focus:outline-none focus:bg-white">$task->description /textarea> if ($errors->has('description')) span class="text-danger"> $errors->first('description') /span> endif /div> div class="form-group"> button type="submit" name="update" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Update task/button> /div> csrf_field() /form> /div> /div>/div>/x-app-layout>After editing this view, all the pieces are joined so you can now thử nghiệm your application.

First register và then login & then kiểm tra if you can create task, edit task và delete task.

13) Run the project in Localhost

To run the project, run this command in the terminal window – php artisan serve. Make sure you are in the root of your application in terminal.