Laravel 5.7.* Model Relations Explained
Total Page:16
File Type:pdf, Size:1020Kb
Laravel 5.7.* Model Relations Explained A DETAILED DISCUSSION OF MVC, COMPOSER, MIGRATIONS, DATABASE RELATIONSHIPS, RESOURCE CONTROLLERS AND FAKER, ADVANCED CRUD, ONE TO ONE, ONE TO MANY, MANY TO MANY, HAS MANY THROUGH, AND POLYMORPHIC RELATIONSHIPS IN LARAVEL 5.7.* Sanjib Sinha Laravel 5.5.* Model Relations Explained Copyright © 2018 by Sanjib Sinha This work is subject to copyright. All rights are reserved by the Writer, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Regarding re-publication of this book, you may contact the author, here, Sanjib Sinha, at this email address: [email protected] While the advice and information in this book are believed to be true and accurate at the date of publication, the author cannot accept any legal responsibility for any errors or omissions that may be made. The author makes no warranty, express or implied, with respect to the material contained herein. Development Editor: Amitakkhar Deb, 12REACH Cover designed by Kaberi Sinha Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book's product page, located at https://github.com/sanjibsinha/laravelmodelrelations About the Author Sanjib Sinha is a certified “.NET Windows and Web Developer”, specializing in Python, Security Programming and PHP; he won Microsoft's Community Contributor Award in 2011. As a published author, Sanjib Sinha has written “Beginning Ethical Hacking with Python”, and “Beginning Laravel” for Apress. Acknowledgments I wish to record my gratitude to my wife, Kaberi, for her unstinting support and encouragement in the preparation of this book. I am extremely grateful to Mr. Amitakkhar Deb, Lead Development Editor of 12REACH, for his numerous valuable suggestions, complementary opinions and thorough thumbing and the whole 12REACH team for their persistent support and help. In the preparation of this book, I have had to consult numerous open source documentation and text-books on a variety of subjects related to PHP, I thank countless authors and writers who have written them. Who should read this book? This book is intended for Intermediate PHP developers. Advanced users may also find this book helpful for some quick references. You should have a good grasp of object- oriented PHP7 programming knowledge. What you will Learn from this Book and The Application we are going to build Apparently, this contents management application does not look very complicated, however, the relations are quite tangled and we will try to understand these relations through Laravel’s Model relations and Eloquent ORM; at the end, we will also learn how resourceful controllers play vital roles in such model relations. How an article is related to a particular user and how from the article table we can fetch the data of that particular user or writer? An article uses many tags, but how we can access those tags from that article itself? An article may have many comments. Who has written those comments? Of course users. And these users have their own profiles which tell us about them, including name, email, city, and a short biography. Each profile page may have multiple comments written by other users about that profile-holder user. So we have comments table for both – articles and profiles. Can we use one single comment table to serve them both? Yes, we can do! A polymorphic relationship allows us to do that. These questions are all very tricky, however, laravel model relations, Eloquent ORM, and resourceful controllers has solved these problems quite easily. As we progress we will learn one-to-one, one-to-many, many-to-many, has-many-through, and polymorphic relationships with concrete examples. By the way, we will also learn some major tricks of Laravel (like resource controller and views) that makes your development experience more pleasant. Finally, what we will see in this application? A user have many articles. When you open the application, you will find the series of article titles. Each title will show who is the writer of it. If you click on each title, you can read the full article. If you click on the user name, you will see the user’s profile and all the articles he/she has written. The same rule is applied for the tags. Each tag may belong to many articles. Again any article may belong to many tags. So each article shows many tags. In the user profile we will see which tags he/she has used often and so on. In addition to that, we have comments on both pages, with a link to the users who have written them. All together, it’s an interconnected contents management application that handles many complex queries effortlessly. Contents 1. What is MVC Pattern 2. How MVC Pattern Works 3. Composer and Laravel 3.1 Composer’s role in Effective Patterns 3.2 Composer and Separation of Concerns 3.3 Laravel Homestead, Virtual Box and Vagrant 3.4 Installing Virtual Box and Vagrant 3.5 Installing Homestead Vagrant Box 3.6 Homestead installation and configuration 4. How to start our Application 5. How Migrations work in Laravel 5.1 Model Relations for Application 5.2 Controllers and Views 5.3 Creating Views to show Relationships 5.4 One To One 5.5 One to Many 5.6 Dependency Injection and Separation of Concerns 5.7 Many to Many 5.8 Has Many Through 5.9 Polymorphic Relations 6. Resource Controllers and Eloquent Magic 6.1 Model and Controller Where to go from here Last but not the Least 1. What is MVC Pattern Implementing user interfaces successfully is our main goal when we build a web application. How we could do this in a decent way, keeping ‘separation of concerns’ principle intact? Model View Controller (MVC) architecture is the answer. It is commonly used and a very popular choice. The ‘separation of concerns’ principle usually separates the application logic from the presentation layers. Likewise, it makes the application more flexible; iterations, which is the core part of our logic flow becomes easier. Quite naturally, our application becomes more flexible, modular, and reusable. Let us imagine a social networking application where you want to view a user’s page. You may click a link and heads out straight to the page where every details are being shown. Imagine a simple URI like this: https://example.com/home/index/username. Here you may imagine that ‘home’ is the controller, ‘index’ is the method and in the ‘username’ section you can even pass an ID. Apparently, it looks simple; you use home controller calling index method and pass an user name or ID. It takes you to the user’s page. How we can make our ‘app’ work through an MVC model? As you guess, we will get the user’s data from a database. Our Model defines what data our application should contain. So, it is Model’s job to interact with the database. Now, a user’s database will constantly evolve, changes will take place, the user will give her updates. If the state of this data changes, the Model will usually notify the View. If different logic is needed to control the View, the Model notifies the controller. Keeping our social media app in mind, the model would specify what data the list item should contain – first name, last name, location, etc. Compared to the functions of Model and Controller, the work-flow of View consists of simple tasks. It would only define how the list is presented to another user. It will also receive the data from Model to display. The role of Controller is critical. It contains logic that updates the Model and sometimes View in response to input from the users of the app. Usually, in other social media app almost same thing happens. The app could have input form-boxes to allow us to post or edit or delete the data. The actions require the Model to be updated, so the input is sent to the Controller, which then acts upon the Model and the Model then sends the updated data to the View. Now, this View can be manipulated in different manner – you can use your layout template engine. In some cases, Controller can handle these tasks independently without needing to update the Model. Actually, we have seen this pattern before. Our data model uses some kind of database; most probably MySQL in LAMP technology. In such cases, our controller’s code is written in PHP and in View part we have used the combination of HTML and CSS. 2. How MVC Pattern Works Imagine a portal, where user interacts with the user interface in some way: clicking a link or submitting a form. Now, the controller takes the charge and handles the user input event from the user interface. Consequently, the controller notifies the Model of the user action. Usually, the state of Model gets changed. Suppose, the Controller updates the status of the user. It interacts with the Model and the model has no direct knowledge of the view. It passes data objects to Controller and then Controller generates the contents gathering that dynamic data. For its simple iterations and the principle of separation of concerns, MVC pattern is often found in web application. Now, the MVC pattern can be interpreted in different ways: a section thinks that the actual processing part is handled by the Model and the Controller only handles the input data.