Git is an essential tool for every developer. In this tutorial, I will explain everything you need to know about branches and conflicts while working in a team, with Laravel examples.
In fact, this article is not about Laravel, it's just that example code will be with Laravel framework, but you can apply Git knowledge from here to other coding languages/frameworks, too.
Notice: in this tutorial, we will use Terminal and not use visual tools like Sourcetree/GitHub Desktop or PhpStorm/VSCode editors. Those tools can help but I want you to learn principles and the syntax if you do need to work with the Terminal.
Start with Branches: Main/Master and Develop
Branches are probably the foundation when working with the team. But even when working solo, you may use branches to work on separate features simultaneously, so you may have branches called "feature-payment", "feature-user-update", etc.
Also, you may use them for testing features from branches without deploying them to live. So, your testing server would get the code from "develop" branch, for example, and you can play around there, until you're sure it works, and then merge the code into the "main" branch for deployment.
Every team choose their own branch names and branch logic, but there's a most typical behavior, here's how it goes.
When the repository is created, it is created with the branch called
Notice: GitHub changed its default from
mainfor new repositories in 2020.
Next, let's create a new fresh Laravel project and push its code to GitHub.
laravel new laravelcd laravel
Now we can push to that
git initgit add .git commit -m "Fresh Laravel"git branch -M maingit remote add origin firstname.lastname@example.org:krekas/Git-Example.gitgit push -u origin main
What every command here does?
- Creates an empty Git repository.
- Adds all files to the repository.
- Makes a commit with the message "Fresh Laravel".
- Sets branch to
- Adds an origin where to push.
- Pushes code to the
If you refresh the GitHub repository page, you will see the code was pushed to the
Next step: usually the
main branch is only for the "finalized" features to deploy to live. And the work is being done in other branches. So, from that
main branch, someone creates a
develop branch where the work is being done. Here's how you can do it on GitHub directly in the browser.
At this point, the
develop code is identical to the
Then, whenever a developer starts working on the project, they clone the repository, check out the
develop branch and starts the work.
main branch is only for deployment to the live server which happens from time to time, but more rarely than everyday work.
You can even protect the branches on GitHub, to restrict pushing to the
main branch, to avoid...