Introduction to Laravel CRUD Operations
Hello friends, this is Laravel tutorial series for beginners and in this part we have start learning CRUD operation in Laravel framework. So in CRUD operation, we will first discuss create or insert data into a MySQL table in Laravel framework.
In the previous part, we have already discussed how to install the Laravel framework by using Composer, and then after, we have discussed how to make a database connection and after this how to create a MySQL table in a Laravel application. So in the previous part, we have already made a database connection with the laravel_testing database and in that, we have already created a simple student table. So we will insert data into this table.
Creating the View with Blade Templating
Now, we will start discussing how to insert data into a MySQL table in a Laravel application. So first, we want to make one view file for inserting form data into the MySQL database.
So here we can see the Laravel directory structure. So we go to the resources folder and in that folder, we go to the views folder, and here we have already created one master.blade.php file. Here, Blade is a simple but very powerful templating engine which is provided in the Laravel framework. So in all Laravel view files, use the .blade extension and it has been stored in a resources/views folder directory.
So this is our master template, or it is the skeleton of our template, in which we have used the Bootstrap library for stylesheet purposes. Because template inheritance is a benefit of Blade templating. Here we have @yield('content'). By using this directive, we can display contents under this part. Now, here under the views folder, we have already created one student folder and under this folder, we have already created one create.blade.php file.
Extending the Master Template
So we have opened this file and now we want to extend the master.blade.php file template under this file. So we simply write @extends('master'). Here create.blade.php is a child page and here we have extended the master.blade.php page by using this @extends directive. So this way we can extend templates in Laravel.
After this, we have the @section directive with content here. This directive defines a section of content, while the @yield directive will display content on a given section. Now first we want to close this section directive, so we have @endsection directive. It will close this directive. Between this we have write some HTML code.
Now we have started to create a form for inserting student data. So here we write a form tag with attribute method="post" and action="{{ url('student') }}". So here we have sent the form request to this student controller.
Under this form, first we have input type="text" with attribute name="first_name" and placeholder="Enter first name". Under this textbox, the user can enter the student's first name. Below, we write input type="text" with attribute name="lastname" and placeholder="Enter last name". Under this textbox, the user can enter the student's last name. Lastly, we want to define a form submit button. So we write input type="submit". By clicking on this button, we can send form data to the student controller, which we will create now.
Generating a Resource Controller
We want to create a student controller for handling form requests. So we go to the command prompt and here we write php artisan make:controller StudentController --resource and press Enter. This command will create a controller file with the name StudentController.php.
To see the controller file we go to the app folder and within this folder we go to the HTTP folder and here we can find StudentController.php which we have created. And under this controller we can see all CRUD functions like index for display data, create function for create new data, store method for insert data into table, show method for display inserted data on a web page, edit method for display inserted data under a form, update method for update existing data, and lastly destroy method for delete data from the table. So in this controller, we can see all methods for CRUD operations.
Defining Resource Routes
Now we want to register this student controller with all method routes under the Laravel application. So we go to the routes folder and under this we open web.php file. Under this file, we write Route::resource('student', 'StudentController').
This is a single routes declaration which creates multiple routes to handle a variety of RESTful actions on the student resource, which we can see on the webpage.
Implementing the create Method
Now in the next step, we go to StudentController.php file and we add some code. So here we have a return statement with the view method and under this, we write student.create. This code will load the create.blade.php view file from the student folder which we have created under this tutorial.
Suppose we want to check the output of this code. So we go to the command prompt and here we write a command like php artisan serve and press enter. Here we can see the URL, so we copy this URL and go to the browser. Here in the browser, we paste this URL and type student/create. So here we can see this output of that student data form on the webpage.
Configuring Mass Assignment Protection
Now we also need to handle mass assignment exception. So we go to the app folder and under this folder we go to the Student.php model file which we have already created in the previous part. Under this student model file we create $fillable protected variable is equal to an array with form field names like first_name and last_name.
After this, we go to StudentController.php file and here we need to include the namespace of the student model. So here we have a use statement with AppStudent model name. This way we have included the namespace of the student model under this student controller.
Implementing the store Method for Data Insertion
Now we proceed for inserting student data. So for inserting data, we have to write code under the store method of the StudentController file. So under this method, we first write validation rules. So here we write $this->validate() with two arguments. In the first argument, we have the $request variable, and in the second argument, we define validation rules like first_name textbox value is required, last_name textbox value required.
So when the form is submitted for inserting student data, then this method will be called and under this, first it will validate both form fields have some value, then it will proceed for inserting data. Otherwise, it will redirect to the create method, which will load the student form with validation errors.
Now we proceed for inserting data. So here we write $student = new Student; and under this object, we define form data like the first_name table column value get from $request->get('first_name'). Here this get method will get the value of the first_name text box. Same way, the last_name table column value get from $request->get('last_name').
After storing form data under this $student variable, now we want to insert it into the student table. So we simply write $student->save(). This method will automatically make an insert query and execute it, and it will insert data into the student table. So this way we can insert data into a MySQL table.
Now we want to redirect to the create form. So here we write a return statement with the back() method with a with() method with two arguments like success and Student data inserted message. This code will redirect to the create student form again with a success or validation message.
Displaying Feedback Messages in the View
Now we want to display success or validation error messages on the create form. So we go to create.blade.php page, and here first we want to display validation errors. So we write an @if directive with the condition like count($errors) > 0. To close this if block of code, here we write the @endif statement. This condition will check if the $errors array has some value, then it will execute this if block of code.
Suppose the above condition is true, then it will execute this block of code, and under this, we have @foreach($errors->all() as $error). By using this directive, we can fetch an error from this $errors variable and display it on the webpage. And to foreclose this directive, we write @endforeach. Under this block, we have a list tag, and between this tag, we write {{ $error }}. It will print all validation errors on this page.
After this, we want to display a success message on the webpage. So we write @if (\Session::has('success')). This condition will check if this session class has method returns success, then it will execute the if block, and it will display the success message on the webpage. For displaying the success message, here we write {{ \Session::get('success') }}. It will display the success message on the webpage. So our code is ready.
Live Demonstration and Verification
So we have saved this code and check the output in the browser. Here friends, we have already started the Laravel application and here we have already loaded the create method. So first, we refresh the page.
After refreshing the page, we can see a simple form for entering student information like first name and last name with a submit button. So we directly click on the submit button. After clicking on the submit button we have received validation errors like first name and last name is required.
So now we write 'John' in first name and 'Smith' in last name and click on the submit button. After submitting the form with data, we have received a success message like 'Student data inserted'. So this way we can insert data into a MySQL table. Now we have seen the MySQL student table and here we can also see data has been inserted in the table also.
Recap and Conclusion
So in this part, we have discussed how to insert data into a MySQL table in a Laravel application. For this, we have first seen Laravel Blade templating, and in that, we have made a master template. And then after, we have extended the master template from a child page. Same way, we have also seen how to create a CRUD controller by using Composer and in that, all CRUD methods were already created. We have also seen simple Laravel validation. And after this, we have inserted data into the table. And lastly, we have seen how to display a validation error or success message on a webpage by using Blade templating.
If you have any query regarding this video tutorial part, please comment your query in the comment box. And if you like this video tutorial, please share with your friends or even you can also share on social media also. If you want to get more updates regarding our video tutorial, please subscribe to our YouTube channel to get more updates regarding the release of future videos. Lastly, keep watching our YouTube channel. Thanks for watching this video tutorial.