Showing posts with label Laravel Seeding Concept. Show all posts
Showing posts with label Laravel Seeding Concept. Show all posts

100 Top Interview Laravel Question for Fresher and Experience

 

100 Laravel Framework Interview Question


1) Describe Laravel?

 Laravel is MVC(Model View Controller) architecture based open Source php Framework developed by Taylor Otwell. Latest version of Laravel Framework is 7.0 which got released on March 3rd.

Laravel 1st version got released on 9th June 2011.



2) What are the Laravel Framework Feature ?

 Top Feature of laravel Framework is below.

  • CRSF (cross-site request forgery )
  • Eloquent ORM
  • Laravel paginations
  • Database Seeding
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • Unit Testing
  • IOC (Inverse of Control) Container.
  • Job middleware
  • Lazy collections



3) Define Laravel Eloquent ORM ?

Laravel Eloquent feature is object Oriented paradigm approach of database communication. In Eloquent we create Model for each Table in the database, which set the communication (Fetching, Inserting, Deleting, Modifying the Record ) with database. It represent Database Table as a Class.



Laravel Eloquent ORM With Example Read More






4) What is Soft Delete? How to use it in Laravel Model?

Soft Delete is feature of laravel framework which helps when model is soft deleted. In this scenario the data record is not deleted form the database table instead deleted_at timestamp is maintained.




5) Define Laravel Query Builder ?

Query Builder in Larevel is a Package through which we create and run database query Quickly to run the application smoothly. Query Bulider Use PHP Data Object (PDO) where we dont have to worry about the SQL Injection. It can perform all Database Operation such as CRUD, DB Connection, Aggregate Function etc.



Laravel Query Builder With Example Read More






6) Explain Middleware Concept in Laravel?

Laravel Middleware provide a filter as well as it act as interface or Middle-Man between HTTP request and response which access the application. Middleware is a way to filter all the bad or Forgery request which try to access your Application.

Laravel Middleware Type 
  • Global Middleware 
  • Route Middleware


Laravel Middleware With Example Read More






7) Define Aggregate Function ? What are the aggregate function available in Lravel Query Builder?

In Aggregate Function, Database Table Rows are grouped together based on certain Criteria to get specific summary value. Laravel Provide various aggregate function which we can use in our query, list is below for your reference.
  • count() function
  • max() function
  • min() function
  • sum() function
  • avg() function
Note: All Aggregate function defined above ignore NULL Value except Count() function.



8) Explain Laravel Migration? Write the Artisan Command for Laravel Migration ?

Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


Artisan Command for Laravel migration.    php artisan migrate



9) Describe Laravel Reverse Routing ?

Laravel reverse Routing is one of the Awesome Route Feature. Reverse Routing is process of generating the URL based on the Route Deceleration. Reverse Routing sets a relationship between links and web routes.

Consider below route declared as Example (consider your Website as www.abc.com)

Route::get('user-login','UserController@userLogin');

{ { url( '/usre-login' ) } }

$url-link = URL::route('usre-login');

$redirect
-link = Redirect::route('usre-login');

Above three will generate the URL which is below as a example :

URL : www.abc.com/user-login

Now reverse routing is process to generate the url based on Name or other parameter.

  {{ HTML :: link_to_action( ' UserController@userLogin ' ) }}  

This above reverse routing will also generate or point the same URL www.abc.com/user-login .

 
10) What is Artisan ? List some Common Php Artisan command?

 Artisan is command line Interface tool which help in laravel Application Building. To Kmow all this List of Artisan command, Use the below Artisan command.

php artisan list

 List of Common Artisan Command for hassle free Laravel application Development is below:-
  • php artisan list
  • php artisan make:controller controller-name
  • php artisan make:model model-name  
  • php artisan migrate
  • php artisan make:middleware middleware-name  
  • php artisan tinker


11) Define Controller ?

Controller handle all the HTTP Request logically and divert the Web Traffic to View and Model. It Contain all the Http Handling Logic within Single Class. Artisan Command to create the Controller is below for your Reference.

php artisan make:controller controllerName

Controller is C of  MVC(Model View Controller).


12) List out some Laravel Official Packages?

Laravel Packages list is below for your reference.
  • Dusk Package
  • Envoy Package
  • Horizon Package
  • Cashier Package
  • Passport Package
  • Scout Package
  • Socialite Package
  • Telescope Package
 

13) What is the difference between find() and where() method in laravel?

The Major Difference between them is find() method always use Primary Key to filter the table record, whereas where() method uses any table column to filter the table record set.

find() method will return the single table row from the database. where() method return multiple record based on the condition.



14) What is Named Route in Laravel ?

Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004



15) Define Laravel Validation?

Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation purpose is to get the exact data what is required for application.

You can use validate method for data filteration.

$validatedData = $request->validate([
            'FULL_NAME' => 'required|max:25',
            'mobile' => 'required|digits:10|unique:valid_table,mobile',
            'email' => 'required|email|max:255',
        ]);

You can use Validation make() method to create manual validator.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



16) Define Route::fallback method with Example?

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});




laravel Seeding and Datatbase from Scratch


Database Migration and Database seeding is one of the most amazing feature of Laravel Framework. Database seeding is feature through which we insert the dummy record / data using Seed Class in the DB table for testing purpose. Seed Classes name can be anything but it is good to follow the standard practice for naming Convention, Example of Seed Classes is UserTableSeeder, UserSeeder etc.

All the Seeder Classes is stored in database / seeds Directory folder. By default DatabaseSeeder is defined in seeds Folder.

Whenever we download the laravel project Folder at that time by default PHP Faker Package is also get installed in the Project folder. Php Faker package help us to generate the Fake data for Database seeding.

Artisan command to create the Seeder Class for populating Data in the table.

php artisan make:seeder seederName

SeederName whatever it get created using Artisan Command will be stored in database / seeds Directory. By Default Seeder class contain only one method that is run().

Artisan Command to run the seed Class is below for your Reference.

php artisan db:seed

php artisan db:seed --class UserTableSeeder

php artisan db:seed artisan command will run the DatabaseSeeder Class by default, which can call other seed class. If you want to run some particular Seed Class to populate the Database table then we have to use php artisan db:seed --class seederName

DatabaseSeeder Class code is below what we get in the database/seeds directory while installing the project.


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()   // By Default Artisan Command will Run This
    {
        // $this->call(UsersTableSeeder::class);
    }
}

How to Implement The Laravel Database Seeding?


Step 1:  Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

Now check your Migration folder inside Database Folder in your laravel project.

In the migration folder the migration file will be created and if you open that you will get default up() function and down() function for the table whatever it is. I have modified the post_masters table by adding First_name and Last_name. 

   public function up()
     {
        Schema::create('post_masters', function (Blueprint $table) {
            $table->increments('id');
            $table->string('First_name', 50);
            $table->string('Last_name', 50);
            $table->timestamps();
        });
     }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_masters');
    }


Method 1st to implement the Database Seeding in Laravel

Step 2: Now go to database / seeds directory and open the default DatabaseSeeder.php file which we get by default. Below is the code for your reference purpose. Start writing the code in the run() function.


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() 
    {
        DB::table('post_masters')->insert([
            'First_name' => Str::random(10),
            'Last_name' => Str::random(10),
        ]);
    }
}

In the above code Str::random(10) will generate random strong which will  have the length 10 Character. Run the Artisan Command for Database table seeding, once it will run It will generate the random string that can be anything which will not have any sense. This Artisan Command will call the run() method by default.

php artisan db:seed

So now we will use PHP Faker package to generate some sensible data in below method.

Method 2nd to implement the Database Seeding in Laravel

In 2nd Method for each Migration Table we will create individual seeding class following the Naming convention using Artisan command and by using PHP Faker package for generating the data.

So Let's start with Example, create separate seeding Class for post_masters  table using Artisan Command. Below is the Command for your reference.

php artisan make:seeder PostMasterSeeder

Once you run the above Artisan command you will get the PostMasterSeeder.php file in database/seeds Directory. Below Code is the reference of  PostMasterSeeder.php. Now we will write the code for our Post_master table to create the fake Data for testing.

use Illuminate\Database\Seeder;
class PostMasterSeeder extends Seeder {     /**      * Run the database seeds.      *      * @return void      */     public function run()     {         //     } }

You can read more about the PHP Faker here Now Open the DatabaseSeeder.php file and call the PostMasterSeeder.php file for seeding.

use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder {     /**      * Run the database seeds.      *      * @return void      */     public function run()     {           $this->call(App\PostMasterSeeder::class, 50);
    } }

Now go to database / factories root folder there by default UserFactory.php will be there. We will create the PostMasterFactory using Artisan Command. Below is the Artisan command for your reference.

                                    php artisan make:model PostMasterFactory   

Above Artisan command will create the Factory for Post_master table. By Default it will give the code which is below for your reference. Above Command will create the Factory without model detail.

use Faker\Generator as Faker; $factory->define(Model::classfunction (Faker $faker) {     return [             ]; });

                        php artisan make:factory PostMasterFactory --model=PostMaster

Above  Artisan command above will create the Factory with model which we can use for Database seeding for particular table.
use Faker\Generator as Faker; $factory->define(App\PostMaster::classfunction (Faker $faker) {     return [         //     ]; });

Now add the code in the above PostMasterFactory.php file.

use Faker\Generator as Faker;
$factory->define(App\PostMaster::classfunction (Faker $faker) {     return [         'First_name' => $faker->firstName,         'Last_name' => $faker->lastName,     ]; });

After doing all the previous Step run the Artisan Command to generate the record. Artisan command is below for your reference.

                                                        php artisan make:seed

Finally it will generate the sensible Fake data in Post_master table.

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post