Book Image

Learning Laravel's Eloquent

By : Francesco Malatesta
Book Image

Learning Laravel's Eloquent

By: Francesco Malatesta

Overview of this book

<p>Learning Laravel's Eloquent starts off by taking you through setting up your first project and guiding you in creating a perfect Laravel environment. You will learn how to build the right database structure with the Migrations system and the Schema Builder class. Next, you will be introduced to the main element of Eloquent: the model. After treating the model as a single, isolated entity, you will learn how to create relations between them. You will be taken through organizing, filtering, and sorting your data with collections. You will then learn to enhance an application with new features using events and by creating new observers. Towards the end of the book, you will discover how to install, configure, and use the Eloquent ORM without Laravel. The book concludes by walking you through how to deal with complex problems and build advanced and flexible systems.</p>
Table of Contents (16 chapters)
Learning Laravel's Eloquent
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Extending the Model: Aweloquent!


The Eloquent Model can actually do tons of things in a very smart and easy way. However, something can be improved in terms of code to write every time you want to do a specific operation.

Usually, when creating a new model instance, you are probably using some data that the user previously typed in to a form.

Adding a new author to our database can be the perfect example. All you have to do is to insert the first and last names in to a form and then press save.

Then, in the dedicated post route (or relative controller method), you will do something similar to the following:

<?php


public function postAdd(Request $request)
{
  $author = new Author;

  $author->first_name = $request->input('first_name');
  $author->last_name = $request->input('last_name');

  $author->save();
}

That's quite fine. However, you will probably also have to validate the user input.

So, assuming that you are still in a controller, you could add a controller validator...