天道酬勤,学无止境

passing variables to laravel service provider

Question

I want to pass a variable on my laravel app from the view to the service provider. The view is:

{!! Form::open(['url'=>'reports/data',$kpi_id]) !!}

    <table class="table table-responsive table-condensed table-bordered tab-content">
        <thead>
            <tr>
                <th>Month</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
            @foreach($data as $dat)
                <tr>{{$dat->month}}</tr>
                <tr>{{$dat->value}}</tr>
            @endforeach
        </tbody>
    </table>

{!! Form::close() !!}

and the code at the service provider is:

public function boot()
{
    $this->composeData();
}

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

public function composeData()
{
    view()->composer('reports.data', function ($view, $id) {
        $view->with('data', DB::table('reports')->where('kpi_id', $id)->orderBy('month', 'desc')->take(5)->get());
    });
}

The error:

Argument 2 passed to App\Providers\DataServiceProvider::App\Providers\{closure}() must be an instance of App\Http\Requests\Request, none given

I tried it with Request but still didn't manage to make it work.

I want to know how to pass the variable from the view to the service provider, or at least how to call the controller method from the service provider. I tried it but failed to make it work. All the help is appreciated.

EDIT

I get the $id from a var variable in the view

Answer1

Assuming that you pass $id through a route, using Router class which is very useful in this case. For example :

use Illuminate\Routing\Router; // include in your ServiceProvider

public function boot(Router $router)
{
    $router->bind('id',function($id){ // route:  /reports/{id}
        $this->composeData($id);
    });
}

public function composeData($id)
{
  $result = DB::table('reports')->where('kpi_id', $id)->orderBy('month', 'desc')->take(5)->get()

   view()->composer('reports.data', function ($view) use ($result) {
    $view->with('data', $result);
});
}

But be carefull, now your view is depend on {id} parameter.

Answer2

I don't know where you are getting id from so I'm assuming it's stored somewhere in the request object. With that said, you can type-hint the request object in the service provider's constructor. Then pass the id into the callback function via the use keyword.

public function __construct($app, \Request $request)
{
    parent::__construct($app);

    $this->request = $request;
}

public function boot()
{
    $this->composeData();
}

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

public function composeData()
{
    $id = $this->request->get('your_id');
    view()->composer('reports.data', function ($view) use($id) {
        $view->with('data', \DB::table('reports')->where('kpi_id', $id)->orderBy('month', 'desc')->take(5)->get());
    });
}

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • Sending additional parameters to callback uri in socialite package for laravel
    Question Im trying to use Socialite package for laravel and I would like to know how to pass additional parameters to callback url. It seems that OAuth allows additional params, but I haven't found any solution for laravel on how to pass them. Currently my methods look like this public function login($provider) { return Socialite::with($provider)->redirect(); } public function callback(SocialAccountService $service, $provider) { $driver = Socialite::driver($provider); $user = $service->createOrGetUser($driver, $provider); $this->auth()->login($user, true); return redirect()->intended('/'); }
  • Laravel5 how to pass array to view
    Question I am confuse as how to pass variable from controller to view. I know there is a lot about this already on stockoverflow but unable to find one that works, please point me in the right direction. Thank you. CONTROLLER class StoreController extends Controller { public function index() { $store = Store::all(); // got this from database model return view('store', $store); } { VIEW // try a couple of differnt things nothing works print_r($store); print_r($store[0]->id); print_r($id); Answer1 public function index() { $store = Store::all(); // got this from database model return view('store
  • How to pass data to all views in Laravel 5?
    Question I want to have some default data accessible in all views in my Laravel 5 application. I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' here but I can't understand what to do. Where should the following code be placed? View::share('data', [1, 2, 3]); Thanks for your help. Answer1 This target can achieve through different method, 1. Using BaseController The way I like to set things up, I make a BaseController class that extends Laravel’s own Controller, and set up various global things there. All other
  • Laravel 5 - global Blade view variable available in all templates
    Question How can I in Laravel 5 make global variable which will be available in all Blade templates? Answer1 Option 1: You can use view::share() like so: <?php namespace App\Http\Controllers; use View; //You can create a BaseController: class BaseController extends Controller { public $variable1 = "I am Data"; public function __construct() { $variable2 = "I am Data 2"; View::share ( 'variable1', $this->variable1 ); View::share ( 'variable2', $variable2 ); View::share ( 'variable3', 'I am Data 3' ); View::share ( 'variable4', ['name'=>'Franky','address'=>'Mars'] ); } } class HomeController
  • Laravel: How to access session value in AppServiceProvider?
    Question Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views. Answer1 You can't read session directly from a service provider: in Laravel the session is handled by StartSession middleware that executes after all the service providers boot phase If you want to share a session variable with all view, you can use a view composer from your service provider: public function boot() { view()->composer('*', function ($view) { $view->with('your_var', \Session::get('var') ); }); } The callback passed as the second argument
  • Load Blade assets with https in Laravel
    Question I am loading my css using this format: <link href="{{ asset('assets/mdi/css/materialdesignicons.min.css') }}" media="all" rel="stylesheet" type="text/css" /> and it loads fine for all http requests But when I load my login page with SSL (https), I get a ...page... was loaded over HTTPS, but requested an insecure stylesheet 'http... Can someone please tell me how do I make blade load assets over https instead of http? Should I be trying to load the assets securely? Or is it not Blade's job? Answer1 I had a problem with asset function when it's loaded resources through HTTP protocol
  • laravel-5 passing variable to JavaScript
    Question is there any ways that JavaScript can get the variable from compact controller Laravel-5. Example: I have the code below: $langs = Language::all(); return View::make('NAATIMockTest.Admin.Language.index',compact('langs')); Can I get this langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put for two functions in the controller. It didn't work. Any help? This is my code by using PHP-Vars-To-Js-Transformer: LanguageController: This is my create and edit function : public function create() { $names = $this->initLang(); Javascript::put([
  • PHP - Laravel dependency injection: pass parameters to dependency constructor
    Question I'm building a Laravel project and in one of the controllers I'm injecting two dependencies in a method: public function pusherAuth(Request $request, ChannelAuth $channelAuth) { ... } My question is really simple: How do I pass parameters to the $channelAuth dependency? At the moment I'm using some setters to pass the needed dependencies: public function pusherAuth(Request $request, ChannelAuth $channelAuth) { $channelAuth ->setChannel($request->input('channel')) ->setUser(Auth::user()); What are the alternatives to this approach? P.S. The code needs to be testable. Answer1 Thanks to
  • Laravel - Set global variable from settings table
    Question I'm trying to store all my settings from my settings table into a global variable, but I'm stucked now(I have no idea what's the next step), this is my actual model and seeder: model - Settings.php class Setting extends Model { protected $table = 'settings'; public $timestamps = false; protected $fillable = [ 'name', 'value', ]; } seeder - SettingsTableSeeder.php class SettingsTableSeeder extends Seeder { public function run() { $settings = [ ['name' => 'title', 'value' => ''], ['name' => 'facebook', 'value' => ''], ['name' => 'twitter', 'value' => ''], ['name' => 'instagram', 'value'
  • Laravel interview questions and answers
    Laravel is a free and open source PHP web framework based on Symfony. It was created by Taylor Otwell and allows developers to write expressive and elegant syntax. Laravel has built-in support for user authentication and authorization, which is missing in some of the most popular PHP frameworks (such as CodeIgniter, CakePHP). Reading the following Laravel interview questions and answers will help you cope with the interview process freely. It can also be used as an assessment or review to consolidate your Laravel knowledge. 1. How to enable query log in Laravel?  Use the enableQueryLog method
  • Laravel interview questions and answers
    Laravel is a free and open source PHP web framework based on Symfony. It was created by Taylor Otwell and allows developers to write expressive and elegant syntax. Laravel has built-in support for user authentication and authorization, which is missing in some of the most popular PHP frameworks (such as CodeIgniter, CakePHP). Reading the following Laravel interview questions and answers will help you cope with the interview process freely. It can also be used as an assessment or review to consolidate your Laravel knowledge. 1. How to enable query log in Laravel? Use enableQueryLog method to
  • Laravel 6.0
    Laravel Learning Exchange QQ Group: 375462817 Preface to this record document The Laravel documentation is very well written, but it seems a bit difficult for novices. You need to combine experience and online articles to read more and carefully to understand better. Read more and peruse the official documents! ! ! This article is similar to an outline. For details, read the official document: Laravel 6.0 docs. ######################################################################################### ######################################################################################### #####
  • Laravel Global Settings Model
    Question I'm working on building a small CRUD app in Laravel 5. I have a few app wide settings such as "SiteTitle" and "BaseURL" I'd like to give my admins the ability to change from the UI. My whole app uses a base.blade.php template that gets extended to the different views+controllers, this is where these settings would most likely be used. Something like: <h1><a href="#">{{ $setting->SiteName }}</a></h1> I have the settings stored in a database table that are tied to a Setting.php model. I'd rather not everyone of my controller methods query the database for these settings to just pass
  • In Laravel, the best way to pass different types of flash messages in the session
    Question I'm making my first app in Laravel and am trying to get my head around the session flash messages. As far as I'm aware in my controller action I can set a flash message either by going Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK? For the case of redirecting to another route, or Session::flash('message', 'This is a message!'); In my master blade template I'd then have: @if(Session::has('message')) <p class="alert alert-info">{{ Session::get('message') }}</p> @endif As you may have noticed I'm using Bootstrap 3 in my app and would like
  • global variable for all controller and views
    Question In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following public function __construct() { // Fetch the Site Settings object $site_settings = Setting::all(); View::share('site_settings', $site_settings); } Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view. Answer1 At first, a config file is appropriate for
  • 91 common Laravel interview questions and answers
    The following are the frequently asked Laravel and PHP-related interview questions, so that novices and experienced candidates can find suitable jobs. 1) What is Laravel? Laravel is an open source and widely used PHP framework. The platform is mainly used to develop web applications using the MVC architecture pattern. Laravel is released under the MIT license. Therefore, its source code is hosted on GitHub. It follows reliable and accurate language rules, so it is a reliable PHP framework. 2) Define Composer. It is an application-level package manager for PHP. It provides a standard format for
  • Simple understanding of Laravel's core concepts-service container, service provider, contract
    Before I write it, I want to complain about it. Laravel's official document is really disgusting. I don't follow the above, and the people who read it have a numb scalp.Let me talk about a few core concepts in laravel first Service container The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection sounds very fancy, and its essence is to inject class dependencies into the class through the constructor or in some cases through the "setter" method. Simply put, the service container is a tool for managing
  • Laravel 5.3: How to use Auth in Service Provider?
    Question I am passing a value in shared view by taking value from table. I need to know user ID for the purpose but Auth::check() returns false. How do I do it? Below is code: public function boot() { $basket_count = 0; if (Auth::check()) { //always false $loggedin_user_id = Auth::user()->id; $basket_count = Cart::getBasketCount(); } view()->share('basket_count', $basket_count); } Answer1 OK turns out that ServiceProviders are not place for such things. The best thing is a Middleware. So if you want to call Auth, create middleware and pass value to views. public function handle($request
  • Auth filter redirecting back to original POST request in Laravel
    Question It seems that Redirect::guest('login') will only work for GET requests. Ie. it will redirect an authenticated user to the original intended URL (GET). In a situation where there is a POST request, is there a way for the auth filter to continue on to POST to a URL after the user has successfully logged on? A simple example: I want to show a form available to anyone to view. Upon hitting the submit button, the auth filter kicks in which will bring a guest to the login page. After successful authentication, I would like the submit request (ie. POST request) to continue onwards. Answer1 I
  • Override a core Laravel 4 class method
    Question Apologies if this is a dumb question as a lot of Laravel 4 is new to me. I'm trying to override a couple of the methods in the core password functionality as I want to define my own password validation rules (hardcoded into core at the time of posting), and change the method of error reporting ($errors array used on other forms, rather than than session-based). So my approach was to create a new class in /app/lib/MyProject/User called Password.php that looks like this: <?php namespace MyProject\User; use Closure; use Illuminate\Mail\Mailer; use Illuminate\Routing\Redirector; use