Laravel - Response management , Database and Logging
This article will continue where we left off in Part 3 of the Laravel tutorial series. Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell.
In this article, we will have a look at response management, view handling, redirections, database integration and logging in the framework. So, let’s dive straight into the code.
Response Management
Every request usually has a response. Laravel provides several different ways to return a response back to the client. Response can be sent either from route or from the defined controller. Let’s look at the code snippet which returns a traditional response:
Route::get('/', function () {
return 'Hello DiscoverSDK;
});
In addition to returning strings from the routes and controllers, we can also return arrays. The framework will automatically convert the array into a JSON response:
Route::get('/', function () {
return [1, 2, 3];
});
Response Objects
Usually, we won't only return basic strings or arrays from the route actions. Instead, we will be returning full Illuminate\Http\Response instances or views.
Returning a full Response instance allows us to modify the response's HTTP status code and the headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, which provides a variety of methods for building HTTP responses:
Route::get('home', function () {
return response('Hello DiscoverSDK, 200)
->header('Content-Type', 'text/plain');
});
Attaching Headers To Responses
Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. So, we may use the header method to add a series of headers to the response before sending it back to the user:
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
Or, we may use the withHeaders method to specify an array of headers to be added to the response:
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);
Attaching Cookies To Responses
The cookie method on response instances allows you to easily attach cookies to the response. For example, you may use the cookie method to generate a cookie and fluently attach it to the response instance like so:
return response($content)
->header('Content-Type', $type)
->cookie('name', 'value', $minutes);
The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie method:
cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Cookies & Encryption
By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If we would like to disable encryption for a subset of cookies generated by our application, we may use the $except property of the App\Http\Middleware\EncryptCookiesmiddleware, which is located in the app/Http/Middleware directory:
protected $except = [
'cookie_name',
];
Redirects
Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
Sometimes we may wish to redirect the user to their previous location, such as when a submitted form is invalid. We can do this by using the global back helper function. Because this feature utilizes the session, we need to ensure that the route calling the back function is using the web middleware group or has all of the session middleware applied:
Route::post('user/profile', function () {
// Validate the request...
return back()->withInput();
});
Redirecting To Named Routes
When we call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector is returned, allowing us to call any method on the Redirectorinstance. For instance, to generate a RedirectResponse to a named route, we may use the routemethod:
return redirect()->route('login');
If our route has parameters, we may pass them as the second argument to the route method:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', ['id' => 1]);
Populating Parameters Via Eloquent Models
If we redirect to a route with an "ID" parameter that is being populated from an Eloquent model, we can simply pass the model itself. The ID will be extracted automatically:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', [$user]);
If you need to customize the value that is placed in the route parameter, we should override the getRouteKey method on your Eloquent model:
public function getRouteKey()
{
return $this->slug;
}
Redirecting To Controller Actions
We can generate redirects to controller actions as well. To do so, simply pass the controller and action name to the action method:
return redirect()->action('HomeController@index');
If the controller route requires parameters, we can pass them as the second argument to the action method:
return redirect()->action(
'UserController@profile', ['id' => 1]
);
Redirecting With Flashed Session Data
Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when we flash a success message to the session. Usually, we create a RedirectResponse instance and flash data to the session in a single, fluent method chain like shown in code snippet:
Route::post('user/profile', function () {
// Update the user's profile...
return redirect('dashboard')->with('status', 'Profile updated!');
});
After the user is redirected, we can display the flashed message from the session. For example, using Blade syntax:
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
Connecting to Database
Laravel framework has made processing with databases smooth. It currently supports below databases:
- MySQL
- Postgres
- SQLite
- SQL Server
The query to the database can be fired using raw SQL, the fluent query builder, and the Eloquent ORM. To understand the all CRUD (Create, Read, Update, Delete) operations with Laravel, we will use a simple student management system.
Configure the database in config/database.php file and create the college database with structure in MySQL as shown in the following table.
Database − College
Table − student
Column Name |
Column Datatype |
Extra |
Id |
int(11) |
Primary key | Auto increment |
Name |
varchar(25) |
We will see how to perform basic CRUD operations in following examples. Let’s create a controller using following command:
php artisan make:controller StudentController --plain
Our controller class will look like:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudentController extends Controller {
public function insertform(){
return view(student_view);
}
public function index(){
$users = DB::select('select * from student');
return view('stud_view',['users'=>$users]);
}
public function insert(Request $request){
$name = $request->input('stud_name');
DB::insert('insert into student (name) values(?)',[$name]);
echo "Record inserted successfully.<br/>";
echo '<a href = "/insert">Click Here</a> to go back.';
}
public function destroy($id) {
DB::delete('delete from student where id = ?',[$id]);
echo "Record deleted successfully.<br/>";
echo '<a href="/delete-records">Click Here</a> to go back.';
}
public function edit(Request $request,$id) {
$name = $request->input('stud_name');
DB::update('update student set name = ? where id = ?',[$name,$id]);
echo "Record updated successfully.<br/>";
echo '<a href = "/edit-records">Click Here</a> to go back.';
}
}
Conclusion
In this article, we studied about response management, view handling, redirections, database integration and logging in the Laravel framework. We studied a basic example of CRUD operations in Laravel using MySQL databases.
There is a lot more to come which we will read in the Part 5 of our Laravel tutorial series which will cover Forms, Localization, Session management, Validation and File Uploading in Laravel. Stay tuned for more !
Recent Stories
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment