Database & EloquentExtra· 40 min read

Relationships & Validation

Connect models (a post has many comments) and validate input cleanly.

What you will learn

  • Define Eloquent relationships
  • Access related data
  • Validate request input

Relationships

Eloquent makes relationships effortless. Define them once on the model, then access related data like a property.

One user has many posts
// In the User model
public function posts() {
    return $this->hasMany(Post::class);
}

// In the Post model
public function user() {
    return $this->belongsTo(User::class);
}

You declare the link once on each model. In the User model, hasMany(Post::class) says "one user owns many posts". In the Post model, belongsTo(User::class) says "each post belongs to one user". These two methods describe the same relationship from both sides.

With those defined, you reach related data as if it were a normal property — no JOIN to write:

Access related data as properties
$user = User::find(1);
$user->posts;          // all of this user's posts — no JOIN written!

$post = Post::find(1);
$post->user->name;     // the post's author name

Because we named the method posts() on the User model, $user->posts gives back that user’s posts. Going the other way, $post->user gives the post’s owner, and $post->user->name steps straight to that owner’s name. Eloquent runs the database query for you behind that simple dot.

Note: Output: $user->posts → a collection of all posts written by user 1. $post->user->name → the name of the person who wrote post 1, e.g. "Asha".

Validation

Validation means checking the user’s input is acceptable *before* you save it — for example, the name must not be empty and the price must be a number. Laravel does this in one line:

Validate input in one line
public function store(Request $request)
{
    $validated = $request->validate([
        'name'  => 'required|max:100',
        'price' => 'required|numeric|min:0',
    ]);
    Product::create($validated);
    return redirect('/products');
}

The $request->validate([...]) call lists each field and its rules as a simple string: 'required|max:100' means "must be present and at most 100 characters", and 'required|numeric|min:0' means "must be present, a number, and not negative". If every rule passes, the clean values come back in $validated and you save them. If any rule fails, Laravel stops, sends the user back to the form, and shows the error messages — you write no if checks at all.

How a validated form submission flows:

  1. The user submits the form and the request reaches the store method.
  2. $request->validate([...]) checks each field against its rules.
  3. If a rule fails, Laravel automatically redirects back to the form with error messages — your saving code never runs.
  4. If all rules pass, the clean data is returned and you save it with Product::create($validated).
  5. Finally you redirect the user on to the next page.

Tip: Validation rules are simple strings (required|email|max:255). If validation fails, Laravel automatically redirects back with the errors — no manual checking. This is the SQL JOINs and PHP validation you learned, made effortless.

Q. How do you get all of a user’s posts with Eloquent relationships?

Answer: With a hasMany relationship defined, $user->posts returns the related posts — Eloquent handles the query for you.

✍️ Practice

  1. Define a hasMany / belongsTo relationship between two models.
  2. Add validation rules to a store method.

🏠 Homework

  1. Model posts and comments with a relationship and validate the comment form.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →