Tag Archives: laravel tutorials for beginners

Send Sms in laravel PHP


Send Sms in laravel PHP : We often need to send Sms for implementing some specific tasks such as sending verification code on user’s phone for confirmation. For implementing sms we need third party service which can provide us services to send sms using their api’s . For now we are going to demonstrate this with the well known twilio sms services – https://www.twilio.com/try-twilio


How to Send Sms in laravel PHP

Here are the steps to send sms in laravel php-

Step 1 :

Create Account on twilio – https://www.twilio.com/try-twilio

Step 2 :

Open composer.json and add the following lines –

"aloha/twilio": "~1.0"

Step 3 :

Now Run The two Commands Below –

  • composer update
  • php artisan config:publish aloha/twilio

Step 4 :

Now open – /app/config/packages/aloha/twilio/twilio.php and the required configuration. You can find the settings on https://www.twilio.com/user/account/voice-messaging

Step 5 :

Now you are ready to send the message as in below example –

$phone = 9112312312**;
Twilio::message($phone, "Hi Thanks For Registration! ");

Laravel Cache


Laravel Cache : Cache is one of the important part of any framework. Cache improves the system’s performance. Laravel has powerful cache mechanism which makes it perfect. Laravel provides a unified API for various caching systems. Laravel cache config file is located at config/cache.php where you can add configurations.
Laravel supports following types of caching-

  • Memcached
  • Redis

Laravel Cache Syntax And Example-

Let us go step by step –

Settings –

Databse :

Add a database setup to create table which will store information for database cache-

Laravel Create Database Cache Table –

Schema::create('cache', function($table) {
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

Memcached –

Add settings for memcached. Go to config/cache.php and add the memcached settings-

Laravel Memcached –

 'memcached' => [
            'driver'  => 'memcached',
            'servers' => [
                [
                    'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100,
                ],
            ],
        ],

You can add your own host name.

Note : Memcached needs http://pecl.php.net/package/memcached to be installed.

Redis

Laravel Cache Redis Settings –

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],
Note : Make sure predis/predis package (~1.0) is installed.

Laravel Cache Example

Let us understand the Laravel Cache functionality with simple Example –

Laravel Cache Syntax

Cache::put(); Accepts three parameters key, value and time in minutes you want to store the cache.

Laravel Cache Syntax –

Cache::put('key', 'value', $minutes);

Here is a simple example –

Laravel Create Cache Example Syntax

Cache::put(); Accepts three parameters key, value and time in minutes you want to store the cache.

Laravel Cache Syntax –

Route::get('/', function()
{
Cache::put('mykey', 'Welcome to Home Page !', 1);
});

Now if you hit the rout url /URL cache will be created but you will see nothing on browser. To check the cache created go to
app/storage/cache folder and check the file created after opening the file you will see the cache data along with content “Welcome to Home Page !”

Laravel Get Cache Example Syntax

Cache::get(); Accepts one parameter key to get the created cache.

Laravel Get Cache Syntax –

Route::get('/', function()
{
Cache::get('mykey');
});

Now if you hit the index url /URL it will return the cache data from cache file create above.

Laravel Create Cache Forever Example Syntax

Cache::forever(); If you want to keep the cache file forever means it will not expire until you delete it.

Laravel Forever Cache Syntax –

Route::get('/', function()
{
Cache::forever('mykey', 'Welcome to Home Page !');
});

Laravel Forget Cache/Delete Cache Example Syntax

Cache::forget(); is used to delete the cache created using the key. It accepts key as input parameter to remove the cache for that key.

Laravel Forget Cache Syntax –

Route::get('/', function()
{
Cache::forget('mykey');
});

Laravel 5 Print Last Query


Laravel 5 Print Last Query : As developer for debugging the queries we often need to print the queries executed in our program which helps us to work more efficiently. In laravel you need to enable query log DB::enableQueryLog();before the query and then you can print queries as $queries = DB::getQueryLog();


Laravel 5 Print Last Query Example And Syntax

Here is simple example of printing queries in laravel –

Laravel 5 Print Last Query :


DB::enableQueryLog();// enable query first

    // Your queries goes here
    // ...

    // Now print Queries executed....
    $queries = DB::getQueryLog();
    foreach($queries as $k=>$query)
    {
        Log::debug(" $k Query - " . json_encode($query));
    }

Which will print all queries executed.

Note : DB::enableQueryLog(); should be enabled before you log.

Laravel pagination


Laravel pagination : Pagination is used to display the dynamic data using links for dynamic results. In other framework you need to work more to implement pagination functionality. Laravel provides rich pagination functionality which you can use to generate pagination links quickly. We are going to explain the simple method to create pagination in laravel using the paginate method.


Laravel pagination Syntax And Example –

Lets create a simple pagination in laravel –

Here is we are going to add pagination in UsersController and added pagination on user’s view-

Laravel pagination Syntax And Example

class UsersController extends BaseController {

    public function userList()
    {
        $this->layout->title = "App Users ";
        $num = 20; // no of results you want to show on each page.
        $usersList = Users::orderby('created_at', 'desc')->paginate($num);
        $this->layout->content = View::make('content.userscontent')->with('usersList', $usersList);
    }

}

Where $num is no of results you want to show on each page.

Now lets display the pagination links on view

Laravel pagination Show Links On Views-

links(); ?>

Here we have displayed the links for pagination.

Laravel Get Url Parameters


Laravel Get Url Parameters : If you are working with laravel, generally you need to access url parameter and their respective values. Laravel provides few simple methods to access url parameters and their values. We will explain the methods available in laravel which are useful in manipulating the url parameters. We will cover how to validate the url parameter whether it consists data or it is null.


Laravel Get Url Parameters Syntax

Here are examples and syntax to get Url parameters. Let us go step by step to learn the things easily –

Get Url Parameters

You can retreive url parameters as below –

Retrieve Url Parameter

$parameter_name = Input::get('parameter_name');

Where parameter_name is name of parameter you want to retrieve from url.


More About Url Parameters

Let’s have look over more example about url parameters here.

Set A default value and Retrieve It

It the value in url parameter is null you can set a default value for that parameter which will return defualt value in case the parameter retrieves null value.

Retrieve Url Parameter

$parameter_name = Input::get('parameter_name','default');

Will return default if the url parameter is null ie. absent.

Check if value isset/exists –

Set Default Input Parameter

$parameter_name = Input::get('parameter_name'); // returns true if value exists
if($parameter_name){

}

Get All Request Values –

If want to retrieve all values in request you can use following method as below-

Retrieve All Url Parameter

$all_params = Input::all(); // returns all params array

it will return all parameters together.

Laravel session


Laravel session – : Let us have a look over session and how it works?
Breif about Session –
Sessions are used to store information on server side which are available throughout the application. Sessions are stored on server side but they are dependent on cookie as session ids are maintained on browser.

Note : Sessions will not work if you delete cookie of the browser as the id of the sessions will be deleted.

Laravel session provides the functionality to store information accross the application. You can store Laravel sessions in files or database.

Tip :Store sessions in database in when you are working with secure data.
Note : Storing sessions in database makes a little bit slower than storing in file system.

Laravel Session – Set/Get Syntax And Example

Let us understand laravel session syntax with example-

Configurations

Session configuration file is config/session.php. Go and add the required parameters.

Here is config/session.php file with default settings-

session.php

session.php


return [

    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,
];

  • files – Files to store sessions located at – storage/framework/sessions
  • Cookies – Stored at client side in encrypted form.
  • Database table – Table to store sessions by default it is “sessions”
  • Secure – By default it is false if you are working with https turn it as true.
  • Memcached/Redis – Used for faster performance as it provides faster storage.
  • Array – Are stored in variables only and not available throughout the application.

Create Session In Laravel –

Here is syntax to create session variable using the session function. put keyword is used to set the session variable.

Syntax

Session::put(Key, value);

Where key is name of key you want to store the value.

Example

$userid = "98234324";
Session::put('userid', $userid);

Retrive Value From laravel Session

Here is syntax to retrive session value –

Syntax

Session::get(Key, value);

Example


$userid = Session::get('userid');
echo $userid;

Which will print98234324

Delete Data from laravel session

forget keyword is used to delete data from sessions.

Here is syntax to delete data from session in laravel –

Syntax

Session::forget(key);

Example


Session::forget('userid');

Which will delete userid from session.

Delete All Data From Session

If you want to clear all variables of session use flush() keyword.

Syntax

Session::flush();

Which will clear all session variables throughout the system.

Store Array Values in Session-

If you are working with array you can use following method to store values as –

Here is syntax to store array-

Syntax

Session::push(key,array);

Where first parameter is key and second parameter is array.

Example

$data = array("name"=>"John","email"=>"john@example.com");
Session::push('userinfo',$data);

Getting array data from session-

Example

$user = Session::get('userinfo');
echo $user[0]['name']."
"; // print John echo $user[0]['email']; // print john@example.com

Updating Array Index In Session-

Use following method to update array index in session –

Example

Session::push('userinfo.name','Lee');

Which will update the array index name’s value as “Lee”

laravel session example get set session variable in laravel

If want to read full documentation about laravel sessions you can refer laravel.com docs – http://laravel.com/docs/5.1/session

Laravel get last inserted Id


Laravel get last inserted Id : If you are working with laravel database tables and performing insert operation on them you can use the following method to get the last inserted id.


Syntax for Laravel get last inserted Id

Below is an insert query example in laravel.

DB::table('users')->insert(array("id"=>$uid,"name"=>$name,"email"=>$email));
$lastInsertedId = DB::connection('mysql')->pdo->lastInsertId();

Which will return the last inserted id in the laravel table.

Laravel Update Query


Laravel Update Query : Laravel Update Query Builder is used to update the existing records in a table.

update() is used to update the records in database table.


Syntax for Laravel Update Query

DB::table('table_name')
    ->where('column_name',value)
    ->update('data_array');

Where –

table_name : Name Of table

column_name: Name Of column and its corresponding value to match it.

data_array: Column Value pair to update the column value.

Laravel Update Query Example

$uid = 10;
$name = "John";
DB::table('users')->update
    ->where("id",$uid)
    ->update(array("name"=>$name));

The above Query will produce the following Result

UPDATE users set name = “John” WHERE id = ’10’;

Get Current date time in laravel


Get Current date time in laravel : You can use datetime class to get current date time in laravel.


Get Current date time in laravel


$date = new DateTime();
echo $date->format('Y-m-d H:i:s');

The above method will give the current date time.