Showing posts with label Laravel 5. Show all posts
Showing posts with label Laravel 5. Show all posts

Friday, March 1, 2019

How to install Laravel 5 with Xampp (Windows)

Requirements
  1. PHP >= 5.5.9
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
Install Xampp
First of all, we need Xampp, so we can download it from the official page: Download Xampp
Install Composer
After you've downloaded and installed Xampp, we need to install Composer.
Composer is a PHP package manager that is integrated with Laravel Framework. In Windows we can install it easy going to the official page and download the installer. Composer Download page

Install Laravel Framework
We are prepared to install and configure a Laravel Framework. First of all, we have to navigate to htdocs folder to install it and run this following command:
composer create-project laravel/laravel laravel "5.1.*"
When it finishes, it will create following directory schema:

Now browse your laravel project into browser:


Friday, February 8, 2019

How to pass data to all views in Laravel 5 | Sharing Data Between Views Using Laravel View Composers | Laravel 5.3 - Sharing $user variable in all views | Passing data to all views | View Composer to pass variable to all views | Passing $variables to multiple views

A view composer is exactly what you're looking for. A view composer allows you to tell your application do x when view y is rendered. For example when pages.buy is rendered anywhere in my application attach $articles.
The main thing is to create a service provider under "project/app/Providers" folder as below:
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view) {
            $view->with('isAdmin', true);
            $view->with('isSupervisor', false);
        });
        /* Make sure you have a view named "index.blade.ctp" in a folder
        named "customFolder" under "project/resources/views" folder.
         */
        view()->composer(array("customFolder.index"), function($view) {
            $view->with("xor", "XOR-1");
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Override setGlobalTo of Laravel Mailer| Laravel Message Sending listener | Laravel Mail Sending Listener | How to create Event for Mail sending in Laravel 5

We need to create event listener for "Illuminate\Mail\Events\MessageSending" event. So our listener file would be under "project/app/Listeners" as below.
<?php
namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Mail\Events\MessageSending;

class MessageSendingListener {
    public function __construct() {

    }

    public function handle(MessageSending $swiftMessage) {
        $server = env("MODE", "LIVE");
        if ($server != "LIVE") {
            $swiftMessage->message->setSubject($swiftMessage->message->getSubject() . " ($server)");
        }
        Log::info("SENDING EMAIL=".$swiftMessage->message->getSubject());
    }
}
The above file will be called before each mail be send. So we can modify or check anything as global option.
Now we require to register event on EventServiceProvider.php file so, open app/Providers/EventServiceProvider.php and copy this code and put in your file.
<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
            'App\Listeners\EventListener',
        ],
        'Illuminate\Mail\Events\MessageSending' => [
            'App\Listeners\MessageSendingListener',
        ],
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);

        //
    }
}
This is all.

Saturday, July 29, 2017

Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel

At first need to create an Job class inside "project/app/jobs" directory. Laravel 5 | How to create Queue and Run Jobs using worker in Laravel | How to execute a job immediately using Laravel Queue | Job Listener Laravel | Schedule And Execute Job Laravel.

Sample job class:


<?php
namespace App\Jobs;

use Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class MyTestJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels, Queueable;

    private $param1;
    private $param2;

    public function __construct($param1, $param2)
    {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }

    public function handle(Mailer $mailer)
    {
        /* After 3 Times Failed, Job Will Be Released From Queue */
        if ($this->attempts() > 3) {
            Log::info("Max try failed");
            return;
        }
        $to_email = "pritomkucse@gmail.com";
        $mailer->send('emails.some_file_name',
            [
                'param1' => "Param1 value",
                'param2' => "Param2 value"
            ],
            function ($message) use ($to_email) {
                $message->from('from@address.domain', 'From Text');
                $message->subject("Test Subject");
                $message->to($to_email);
            });
    }
}

Below line is to schedule job with 30 seconds delay:

app("Illuminate\\Contracts\\Bus\\Dispatcher")->dispatch((new MyTestJob("1", "2"))->delay(30)); 

And this is time to start queue for job listen. Open command prompt and navigate to "laravel_project"/"project" and execute following command:

php artisan queue:listen --timeout=120

And every time a new job scheduled, this command will execute them on time. 

Saturday, July 22, 2017

Laravel 5 : Get Session Value | Another Session Value | Another Session Instance | Session Instance | HTTP Session | Session Mock | Mock Session | Duplicate Session | SessionManager | StartSession | Session Config | Get Session Config

Laravel 5 : Get Session Value | Another Session Value | Another Session Instance | Session Instance | HTTP Session | Session Mock | Mock Session | Duplicate Session | SessionManager | StartSession | Session Config | Get Session Config.


$sm = app("\\Illuminate\\Session\\SessionManager");
print_r($sm->getSessionConfig());

$sm = new \Illuminate\Session\SessionManager(app());
$ss = new \Illuminate\Session\Middleware\StartSession($sm);
$rq = \Illuminate\Http\Request::create("/", 'GET', array());
$ts = $ss->getSession($rq);
$ts->setId("7fe8a41c8185ef91e1c2b6aaab547ff34f2fed33");
$ts->start();
$ts->set("x", "value of x");
$ts->save();
print_r($ts->all());

And output below:


Array
(
    [driver] => file
    [lifetime] => 1440
    [expire_on_close] => 
    [encrypt] => 
    [files] => ...\project\storage\framework/sessions
    [connection] => 
    [table] => sessions
    [lottery] => Array
        (
            [0] => 2
            [1] => 100
        )

    [cookie] => laravel_session
    [path] => /
    [domain] => 
    [secure] => 
)
Array
(
    [_token] => Bm0Gu0lfy9JVI9TyQnddZVxBe3wndiiUR2NkDd9P
    [url] => Array
        (
        )

    [_previous] => Array
        (
            [url] => http://my_domain.com
        )

    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d] => 371
    [tz] => Asia/Dhaka
    [Hi] => Hello
)

Laravel 5 Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session | PHP Raw Session

Laravel 5 Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session | PHP Raw Session.


$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->setId("b858d2e0f84942ea2a3bb34bf2aa2a176f06b0c6");
$session->start();

$session->set("updated_time", date("Y-m-d H:i:s"));
$session->save();

echo session()->getId();
echo "<BR>";
print_r($session->all());

You can set Laravel default session save path using below example:



public function test(\Illuminate\Config\Repository $config)
{
    session_save_path($config->get("session.files"));
    $session = new \Symfony\Component\HttpFoundation\Session\Session();
    $session->setId("b858d2e0f84942ea2a3bb34bf2aa2a176f06b0c6");
    $session->start();

    $session->set("updated_time", date("Y-m-d H:i:s"));
    $session->save();

    echo session()->getId();
    echo "<BR>";
    print_r($session->all());
}

Tuesday, July 11, 2017

Laravel 5: Get Controller Name in View | Route Details | Controller & Action Name | Route Parameters

You can create a view composer that injects those variables into your view file. In "app/Providers/AppServiceProvider.php" add something like this:

public function boot()
{
    //app('view')->composer("folder.specific_view_name", function ($view) {
    app('view')->composer("*", function ($view) {
        $action = app("request")->route()->getAction();

        $controller = class_basename($action["controller"]);

        list($controller_name, $action_name) = explode("@", $controller);

        $view->with(compact("controller_name", "action_name"));
    });
}

You also can parameters from current request as below:

app('request')->route()->parameters()

Array
(
    [middleware] => web
    [as] => folder.view_name
    [uses] => App\Http\Controllers\UserController@show
    [controller] => App\Http\Controllers\UserController@show
    [namespace] => App\Http\Controllers
    [prefix] => 
    [where] => Array
        (
        )


)


Thursday, July 6, 2017

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method.

Logging query in Laravel is easy. You can then register event listener for DB. At first you need to create an service provider in directory ("project/app/Providers" ) named QueryLogProvider with following contents:


<?php
namespace App\Providers;

use Monolog\Logger;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\StreamHandler;
use Illuminate\Support\ServiceProvider;

class QueryLogProvider extends ServiceProvider
{
    public function register()
    {
        DB::listen(function ($query) {
            $logFile = storage_path('logs/query-log-'.date("Y-m-d").'.log');
            $stream = new Logger('log');
            $stream->pushHandler(new StreamHandler($logFile));
            $bindings = $query->bindings;
            $time = $query->time;
            $stream->info($query->sql, compact('bindings', 'time'));
        });
    }
}

You are done with creating provider. Now you have to register in file "project/config/app.php" in section 


'providers' => [
    .....,
    App\Providers\QueryLogProvider::class
],

All your queries will be stored on the location "project/storage/logs" with prefix file name "query-log".

But you can do some wired things, editing source code. To do so first need to open your connection class:

Illuminate\Database\Connection

and navigate to function:

protected function run($query, $bindings, Closure $callback)

actually all query in Laravel passed through this method.

So you can do whatever you wish to do here.

Monday, July 3, 2017

Laravel 5: Get Service Instance In Controller Dynamically | Get Service Instance In Service Dynamically

The Laravel service container is a powerful tool for managing class dependencies. Dependency injection is a fancy word that essentially means this: class dependencies are "injected" into the class via the constructor.

There are several ways to resolve something out of the container. First, you may use the make method as below example:

$service = app()->make("App\\Service\\EmployeeService");

So it makes life easier.

Friday, June 30, 2017

Laravel 5: Change Default Database connection Dynamically | Change database name of connection on the fly | How to change default database connection in controller | Multiple DB Connections | Specifying DB connection information dynamically instead of config key | How to Use Multiple Database Connections in Laravel Application

use Illuminate\Config\Repository;

public function __construct(Repository $config) {}


So now you can $config from the above reference.

Below is a sample usage of change database name:

$config->set("database.connections.mysql.database", "test");

or

app()->config->set("database.connections.mysql.database", "test");

You can use this functionality in middle-ware.

If your app already connected then you have to disconnect it before make new connection available.

Below follow steps to disconnect connection:

$dm = app("Illuminate\\Database\\DatabaseManager");

$dm->disconnect();

Laravel 5: How to set and get config variable in Controller | Use of Application Config in Controller

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Config\Repository;

public function __construct(Application $app, Repository $config) {}

So now you can $app and $config from the above reference.

Below is a sample usage of $config:

$config->set("database.connections.mysql.database", "test");

Laravel 5: Fluent Query Builder Join with subquery

Laravel is a strong php based framework today. Below is a code sample showing how raw query used for join.

$list = DB::table("users AS u")
    ->join(DB::raw('(SELECT id AS oid,name FROM organization) o'), function($join) {
        $join->on('o.oid', '=', 'u.organization_id');
    })
    ->where("o.oid", 15)
    ->limit(10)
    ->orderBy("u.id", "DESC")
    ->select("u.id", "o.oid", "o.name")
    ->get();


Tuesday, June 27, 2017

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array. You can use the merge() method on the $request object. In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that. 

A few times I encountered a situation – a store() or update() method with Request parameter, but I needed to add some additional value to the request before calling Eloquent functions. So how to do that? Apparently, pretty easy.

use Illuminate\Http\Request;

protected $request;

public function __construct(Request $request)
{
    $this->request = $request;

}

$this->request->merge(["custom" => "New Custom Value"]);






..

Sunday, June 25, 2017

Laravel 5: Generate a URL to a controller action

It's easy to generate a URL as like Controller Action. Suppose you have a controller named "UserController" and have an action inside the Controller named "customerLogin" and in routes.php you mentioned the router as: 

"Route::get("login_customer", "UserController@customerLogin"

So when you browse www.domain.com/login_customer then actually executed "customerLogin" action of "UserController".

Now for some reason you need to construct a URL based on Controller and Action, then you can apply below to generate URL:

action('UserController@customerLogin', ['id' => "3 0"])

Will generate below URL:

www.domain.com/login_customer?id=3+0

If you Controller exists inside another folder then you ca

action('Folder\UserController@customerLogin', ['id' => "3 0"])


Laravel 5: Use of Laravel Middleware WEB | API | THROTTLE

You have to create a middleware first. Create a php file named "ApiFilter.php" in "app/Http/Middleware" folder with following contents:


<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request as HttpRequest;

class ApiFilter
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle(HttpRequest $request, Closure $closure)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            }
            else {
                return redirect()->guest('login');
            }
        }
        return $closure($request);
    }
}


Now you have to register this middleware to your project. Need to open "App\Http\Kernel.php" file. If you want to register this middleware for global scope then you have to add the below line as follows:


protected $middleware = [
    \App\Http\Middleware\ApiFilter::class
];


So when you browse any url in your project scope, this middleware can handle them.

But if you want to the middleware for specific area you have to add the middleware to "$middlewareGroups" as follows:


protected $middlewareGroups = [
    'web' => [
        .....
    ],

    'api' => [
        'throttle:3,1',
        \App\Http\Middleware\ApiFilter::class
    ],
];


Now add the following lines to "app\Http\routes.php":


Route::group(["middleware" => "api", "prefix" => "api"], function() {
    Route::get('action_name', 'ApiController@action_name');
});


If you browse "www.domain.com/api/action_name" it will pass through ApiFilter middleware bacause of prefix "api" used. But if you only browse "www.domain.com/action_name" it will pass through another middleware.



These middleware may be assigned to groups or used individually


protected $routeMiddleware = [
    'my_middleware' => \App\Http\Middleware\Authenticate::class
];

And can be used as below:

Route::group(['middleware' => 'my_middleware'], function() {
    Route::get('landing-page', 'MyController@landingPage');
});


We can use "throttle" which will restrict request overloading. Here we used "throttle:3,1" means per minute 3 request can be granted, if more request send request rejected as below image:

We need to add below line to "routeMiddleware" for "throttle" action:


protected $routeMiddleware = [
    .........,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];