Use Responsable interface in Laravel:
In Laravel 5.5 version, we can use Responsable interface for responses. The toResponse method returns the instance of use Illuminate\Contracts\Support\Responsable.
This tutorial makes your website more secure using Responsable interface. Laravel allows converting data from Controller to an HTTP. In this tutorial, I will show you to retrieve results and display in a page by using Responsable interface in your Laravel web application. Follow the examples and codes:
Create Route:
After connection database in your Laravel project, define a route in web.php. So, open the web.php page and add this codes. Such as:
Route::get('interface','TestController@use_interface');
Here I have written a controller name that is TestController and a function name use_interface. So, you need to create TestController page.
- Create Controller: open command prompt and type – php artisan make:controller TestController. For example:
D:\laravel\test5.5>php artisan make:controller TestController
Controller:
In the controller call the function name which you have to define in the Route then call the Model class name, which Model you are accessing. Here I have a model page UserModel so, I called the model class in Controller page by using App\UserModel below of the namespace App\Http\Controllers.
Now I create a Responses folder inside the HTTP folder and create a file in the Responses folder for interface.
Get all the table records in the public function and return records into the HTTP\Response\ TestResponses.php page.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\UserModel; use DB; use App\Http\Responses\TestResponses; class TestController extends Controller { // public static function use_interface(){ $data=UserModel::get(); return new TestResponses($data); } }
Now go to the TestResponses.php page.
TestResponses.php Page:
In the TestResponses page use Illuminate\Support\Collection and use Illuminate\Contracts\Support\Responsable below the Namespace. Here create a public function toResponse() and return the results to the view page, where you will display all results. Such as:
<?php namespace App\Http\Responses; use Illuminate\Support\Collection; use Illuminate\Contracts\Support\Responsable; class TestResponses implements Responsable{ protected $mainvar; public function __construct(Collection $var){ $this->mainvar = $var; } public function toResponse($request){ return view('home')->with('mainvar',$this->mainvar); } }
Model:
Now go to the model page and connect the database table using this code protected $table=”my_table”, which table record you want to get.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserModel extends Model { // protected $table="my_table"; public $timestamps=false; }
View page:
@foreach($mainvar as $val) {{$val->name}} @endforeach