Skip to main content

Top interview questions on Laravel Eloquent

 Here are some interview questions related to Laravel Eloquent, along with sample answers:

  1. What is Laravel Eloquent?

Answer: Laravel Eloquent is an object-relational mapping (ORM) library included with the Laravel PHP framework. It provides an expressive, fluent interface for interacting with databases using PHP syntax, allowing developers to query and manipulate database records using Eloquent models.

  1. What are the key features of Laravel Eloquent?

Answer: Some key features of Laravel Eloquent include:

  • Easy database querying using PHP syntax.
  • Automatic creation of SQL queries based on method calls.
  • Relationships between database tables using Eloquent relationships (e.g., one-to-one, one-to-many, many-to-many).
  • Eloquent events for hooking into model lifecycle events (e.g., creating, updating, deleting).
  • Accessor and mutator methods for manipulating attribute values before saving or retrieving them from the database.
  • Eager loading of related models to reduce database queries.
  1. Explain the process of defining an Eloquent model in Laravel.

Answer: To define an Eloquent model in Laravel, you create a new PHP class that extends the Illuminate\Database\Eloquent\Model class. You can then define the table associated with the model, as well as any relationships, attributes, accessors, mutators, and other methods required for interacting with the database.

namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'users'; // Define relationships, attributes, and methods here }

  1. How do you define relationships between Eloquent models in Laravel?

Answer: Relationships between Eloquent models are defined using Eloquent's relationship methods (hasOne, hasMany, belongsTo, belongsToMany, etc.). These methods define the type and structure of the relationship between two models, allowing you to easily retrieve related records.

class Post extends Model { public function user() { return $this->belongsTo(User::class); } }

  1. Explain the difference between eager loading and lazy loading in Laravel Eloquent.

Answer: Eager loading and lazy loading are techniques used to retrieve related models in Laravel Eloquent:

  • Eager loading retrieves all related models upfront using a single query, reducing the number of database queries required.
  • Lazy loading retrieves related models on-demand as they are accessed, resulting in additional database queries for each relationship accessed.
  1. What are accessors and mutators in Laravel Eloquent?

Answer: Accessors and mutators are methods defined on Eloquent models for manipulating attribute values before they are saved to or retrieved from the database. Accessors are used to format attribute values when retrieving them, while mutators are used to modify attribute values before they are saved to the database.

class User extends Model { public function getNameAttribute($value) { return ucfirst($value); } public function setPasswordAttribute($value) { $this->attributes['password'] = bcrypt($value); } }

  1. How do you perform database querying using Laravel Eloquent?

Answer: Laravel Eloquent provides a fluent interface for building and executing database queries using PHP syntax. You can use methods like all(), find(), where(), orderBy(), paginate(), etc., to query records from the database.

// Retrieve all users $users = User::all(); // Retrieve a single user by ID $user = User::find(1); // Retrieve users with a specific condition $users = User::where('status', 'active')->get();

Many To Many Polymorphic Relations ,explain with example.

Many-to-many polymorphic relations in Laravel allow a model to belong to many other models on a polymorphic basis, and vice versa. This means that a single model can be related to multiple types of other models, and those other models can be related to multiple instances of the single model


Let's consider a real-life scenario of a social media platform where users can post various types of content, such as posts, articles, and events. Users can also add tags to their content to categorize and make it easier to discover.


In this scenario, we'll model the relationships using many-to-many polymorphic relations.


users table:


id

name

email

(other user-related fields)

posts table:


id

user_id (foreign key)

title

content

articles table:


id

user_id (foreign key)

title

content

events table:


id

user_id (foreign key)

title

description

start_date

end_date

tags table:


id

name

taggables table (pivot table):


tag_id

taggable_id

taggable_type

Now, let's define the relationships in the Eloquent models:


User model:


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class User extends Model

{

    public function posts()

    {

        return $this->hasMany(Post::class);

    }


    public function articles()

    {

        return $this->hasMany(Article::class);

    }


    public function events()

    {

        return $this->hasMany(Event::class);

    }

}


Post model:

namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Post extends Model

{

    public function user()

    {

        return $this->belongsTo(User::class);

    }


    public function tags()

    {

        return $this->morphToMany(Tag::class, 'taggable');

    }

}



Article model:

namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Article extends Model

{

    public function user()

    {

        return $this->belongsTo(User::class);

    }


    public function tags()

    {

        return $this->morphToMany(Tag::class, 'taggable');

    }

}


Event model:


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Event extends Model

{

    public function user()

    {

        return $this->belongsTo(User::class);

    }


    public function tags()

    {

        return $this->morphToMany(Tag::class, 'taggable');

    }

}


Tag model:

namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Tag extends Model

{

    public function posts()

    {

        return $this->morphedByMany(Post::class, 'taggable');

    }


    public function articles()

    {

        return $this->morphedByMany(Article::class, 'taggable');

    }


    public function events()

    {

        return $this->morphedByMany(Event::class, 'taggable');

    }

}


Now, you can use the relationships to attach and retrieve tags for each type of content, just like in the previous example. For example:


$post = Post::find(1);

$post->tags()->attach([1, 2, 3]); // Attach tags to a post


$article = Article::find(1);

$article->tags()->attach([1, 4, 5]); // Attach tags to an article


$event = Event::find(1);

$event->tags()->attach([2, 3, 5]); // Attach tags to an event


This setup allows for a flexible tagging system where tags can be associated with multiple types of content, and content can have multiple tags.






Comments

Popular posts from this blog

MySQL's ACID compliance

Mysql acid compliance ACID is an acronym that stands for four key properties of database transactions: Atomicity Ensures that a transaction is treated as a single, indivisible unit of work Either all operations within a transaction are completed successfully, or none are If any part of the transaction fails, the entire transaction is rolled back to its previous state Prevents partial updates that could leave the database in an inconsistent state Consistency Guarantees that a transaction brings the database from one valid state to another valid state All data written to the database must adhere to defined rules, constraints, cascades, triggers, and other database integrity mechanisms Ensures that any transaction will not break the database's predefined rules Isolation Determines how and when changes made by one transaction become visible to other transactions Prevents interference between concurrent transactions MySQL provides different isolation levels: Read Uncommitted Read Commit...

PHP OOPs exercise - Basic Oops

  Here are key PHP OOP (Object-Oriented Programming) exercise questions with solutions: Basic Class and Object Exercise: // Create a simple bank account class class BankAccount {     private $accountNumber;     private $balance;     public function __construct($accountNumber, $initialBalance = 0) {         $this->accountNumber = $accountNumber;         $this->balance = $initialBalance;     }     public function deposit($amount) {         if ($amount > 0) {             $this->balance += $amount;             return true;         }         return false;  ...

Interview questions for Senior PHP Developer particle41.com

1.Self Introduction 2.Basic questions on session and cookie. 3.Where is session stored? 4.Difference between Cookie and session. 5.Will there be any session before session start? 6.Post Max execution time.How can we modify it? 7.We have a string, "BJFSJK".Without any php function reverse it with half the string length.   To reverse the string with half the string length without using any PHP functions, you can implement a simple algorithm to achieve the desired result. Here's how you can do it: Initialize two pointers, one at the beginning of the string and the other at the midpoint of the string. Swap characters between these two pointers iteratively, moving the pointers towards each other until they meet or cross each other. Here's the PHP code to implement this algorithm:  <?php $string = "ABC100"; $length = strlen($string); // Calculate the midpoint of the string $midpoint = (int)($length / 2); // Initialize pointers $start = 0; $end = $length - 1; //...