- Controller Creation: We generate a resource controller using Artisan. Resource controllers simplify the creation of CRUD (Create, Read, Update, Delete) operations by providing a standard set of methods.
- Defining Methods: In
TaskController, we implement several methods:index(): Returns all tasks from the database.store(Request $request): Accepts a request with task data, creates a new task, and returns it with a 201 status.show($id): Retrieves a specific task by its ID.update(Request $request, $id): Updates a task based on incoming data and returns the updated task.destroy($id): Deletes a task and responds with a 204 status (no content).
Author: saqibkhan
-
Creating a Controller
-
Defining Routes
- API Routes: We define routes in
routes/api.phpusing theapiResourcemethod. This method automatically sets up all the necessary routes for our RESTful API:- GET
/api/tasksfor retrieving tasks. - POST
/api/tasksfor creating a new task. - GET
/api/tasks/{id}for retrieving a specific task. - PUT
/api/tasks/{id}for updating a task. - DELETE
/api/tasks/{id}for deleting a task.
- GET
- API Routes: We define routes in
-
Creating a Migration for Tasks
- Migration Creation: We use Artisan to create a migration file for the
taskstable. Migrations allow us to define the structure of the database in PHP code, making it easy to version control database changes. - Schema Definition: In the migration file, we define the schema for the
taskstable, which includes:id: An auto-incrementing primary key.title: A string to store the task title.description: A nullable text field for additional details.completed: A boolean to track if the task is finished (defaulting tofalse).timestamps: Automatically managed fields for created and updated times.
- Running the Migration: By running
php artisan migrate, we apply this migration, creating thetaskstable in the database.
- Migration Creation: We use Artisan to create a migration file for the
-
Creating a Model
- Task Model: The model acts as an interface between the application and the database. By creating the
Taskmodel, we enable Eloquent ORM functionalities, which allow for easy database interactions.
- Task Model: The model acts as an interface between the application and the database. By creating the
-
Setting Up Laravel
- Installation: We start by using Composer to create a new Laravel project called
task-manager. This command sets up the basic structure of a Laravel application, including necessary directories and configuration files.
- Installation: We start by using Composer to create a new Laravel project called
-
Action URL
Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directly enable you access the controller.
The syntax used in Laravel 5.6 version is as shown −
<?php $url = action('UserController@profile', ['id' => 1]);The similar action called in Laravel 5.7 is mentioned below −
<?php $url = action([PostsController::class, 'index']);One advantage with the new callable array syntax format is the feature of ability to navigate to the controller directly if a developer uses a text editor or IDE that supports code navigation.
-
Dump Server
Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.
With release of version 5.7, you’ll get this command which includes a concept out-of-thebox which allows user to dump data to the console or an HTML file instead of to the browser. The command execution is mentioned below −
php artisan dump-server # Or send the output to an HTML file php artisan dump-server --format=html > dump.htmlExplanation
The command runs a server in the background which helps in collection of data sent from the application, that sends the output through the console. When the command is not running in the foreground, the dump() function is expected to work by default.
-
Pagination Customizations
Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatically takes care of setting the required limit and the defined offset. It accepts only one parameter to paginate i.e. the number of items to be displayed in one page.
Laravel 5.7 includes a new pagination method to customize the number of pages on each side of the paginator. The new method no longer needs a custom pagination view.
The custom pagination view code demonstration is mentioned below −
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class UserController extends Controller{ /** * Show all of the users for the application. * * @return Response */ public function index() {
} }$users = DB::table('users')->paginate(15); return view('user.index', ['users' => $users]);The new pagination customization as per Laravel standards is mentioned below −
<?php User::paginate(10)->onEachSide(5);Note that onEachSide refers to the subdivision of each pagination records with 10 and subdivision of 5.
-
How can you make real time sitemap.xml file in Laravel?
You can create all web pages of a website to tell the search engine about the organizing site content. The crawlers of search engine read this file intelligently to crawl a website.
-
Artisan Commands
Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below −
class ArtisanCommandTest extends TestCase{ public function testBasicTest() {
} }$this->artisan('nova:create', [ 'name' => 'My New Admin panel' ]) ->expectsQuestion('Please enter your API key', 'apiKeySecret') ->expectsOutput('Authenticating...') ->expectsQuestion('Please select a version', 'v1.0') ->expectsOutput('Installing...') ->expectsQuestion('Do you want to compile the assets?', 'yes') ->expectsOutput('Compiling assets...') ->assertExitCode(0);Explanation of Code
Here a new class named “ArtisanCommandTest” is created under test cases module. It includes a basic function testBasicTest which includes various functionalities of assertions.
The artisan command expectsQuestion includes two attributes. One with question and other with an apiKeySecret. Here, the artisan validates the apiKeySecret and verifies the input sent by user.
The same scenario applies for the question “Please select a version” where a user is expected to mention a specific version.