Friday, February 8, 2019

Laravel 5 Check if request is ajax request | Ajax request validation


<?php
use Illuminate\Support\Facades\Request;

return Request::ajax(); /* True | False */




Getting url() in a Command returns http://localhost | URL generated in a queue - localhost returned | URL in jobs only return localhost | URL problem with queued jobs

First need to specify url to project/config/app.php as below:

<?php
return [
    'url' => 'http://localhost:81/my_laravel_project/'
];

Now need to modify project/app/Providers/RouteServiceProvider.php as below:


<?php
namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        parent::boot($router);

        $url = $this->app['url'];
        $url->forceRootUrl(config('app.url'));
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}

Using custom monolog handlers in Laravel

You can easily add new handlers to Monolog


$manage_monolog = function(\Monolog\Logger $monolog) {
    #New monolog file name
    $filename = storage_path('logs'.DIRECTORY_SEPARATOR.'custom.log');
    $handler = new \Monolog\Handler\RotatingFileHandler($filename);

    #If you only keep this handler only
    $monolog->setHandlers(array($handler));

    #If you need to add this custom handler to existing handlers
    $monolog->pushHandler($handler);

    print_r($monolog->getHandlers());
};
$manage_monolog(\Illuminate\Support\Facades\Log::getMonolog());
\Illuminate\Support\Facades\Log::info("Its completed...");



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()
    {
        //
    }
}

Laravel :: Getting url() in a Command returns http://localhost | URL problem with queued jobs | Url helper functions that are relative to application url config | Localhost url problems

First need to configure project/config/app.php as below:
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => 'http://localhost:81/my_project/'
Now need to edit project/app/Providers/AppServiceProvider.php as below:
namespace App\Providers;

use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
    private static $logStream;


    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));
    }
}

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.

Laravel, get last insert id using Eloquent | laravel 5.2 get insert id from eloquent model | Get Last Inserted ID With Example

We have needed some it last inserted ID in Laravel application. so, here we have find 4 different way to get last inserted ID in Laravel. you can use it and get last ID of inserted record in Laravel application.
Using lastInsertId() method
DB::table('users')->insert([
    'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();
Using create() method
$data = User::create(['name'=>'first']);
$id = $data->id;
Using save() method
$data = new User;
$data->name = 'Test';
$data->save();
$id = $data->id;
Using insertGetId() method
$id = DB::table('users')->insertGetId([
    'name' => 'first'
]);