I can access a function in every view like this.
In my AppServiceProvide Code
public function boot()
{
$post = Post::latest()->first();
View::share(compact('post'));
}
How can i access it in every controller?
What is the best way to call a function in every controller,as i need to make sure latest record from database.
**You can write in model also using model object**
public function YourFunction(){
return "data";
}
**call it in your controller like this make model object suppose your
model name is YourModel in controller you can call like this**
$model = new YourModel();
$data = $model->YourFunction(); //calling method in controller
Related
I have and function like this, and I am using this through API and send request object.
public function test(Request $request){
//code
}
now I want to use the same function in another function like this
public function test2(){
$id = 2;
$this->test($id);
}
but in above I need to pass an id.
but the first function expects an argument type of request instance.
How can it be done? and I can't add second argument.
If you are not allowed to edit the method code for some reason, you can do the following:
Create a new Request instance.
Add id property to it with the value.
Call your method.
The Illuminate\Http\Request class has a capture() method which is like below:
/**
* Create a new Illuminate HTTP request from server variables.
*
* #return static
*/
public static function capture()
{
static::enableHttpMethodParameterOverride();
return static::createFromBase(SymfonyRequest::createFromGlobals());
}
In your code, you would do like below:
<?php
use Illuminate\Http\Request;
class xyz{
public function test(Request $request){
//code
}
public function test2(){
$request = Request::capture();
$request->initialize(['id' => 2]);
$this->test($request);
}
}
You should export your code in another function and then use a Trait in each of your controller. Therefore you will have access to the same function in two different classes.
By doing this, you can give whatever argument you want, even set defaults one without calling the controller function itself.
The official doc about Trait
The best practice would be to create a third private method in the controller (or in a separate class, as you prefer) that is called by both functions:
class TestController extends Controller {
public function test(Request $request){
$id = $request->get('id', 0); // Extract the id from the request
$this->doStuffWithId($id);
}
public function test2(){
$id = 2;
$this->doStuffWithId($id);
}
private function doStuffWithId($id) {
// code
}
}
You can and should organize your shared code across multiple controllers with services. Basically create class
<?php
namespace App\Services;
class TestService
{
public function testFunction($id)
{
// add your logic hear
return 'executed';
}
}
and in your controller inject this service and call function testFunction() like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\TestService;
class TestController
{
protected $testService;
public function __construct(TestService $testService)
{
$this->testService = $testService;
}
public function test(Request $request){
// handle validation, get id
$this->testService->testFunction($id);
// return response from controller (json, view)
}
We want to pass data from controller to another controller in Laravel (framework). In our Controller.php we got a middleware code in the __construct function, which sets a environment and person.
Code in Controller.php
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->environment = session()->get('environment');
$this->person = session()->get('person');
return $next($request);
});
}
In a different controller we pass 2 parameters (Request data) and (id of data) to another controller function. We tried many ways for pass data. On this moment we lost our $this data like environment and person, the variables environment and person are exists but empty.
We tried with:
$postController = new \App\Http\Controllers\Publication\Post\IndexController();
$postController->duplicate($request, data_get($publication, 'id'));
Or
app('App\Http\Controllers\Publication\Post\IndexController')->duplicate($request, data_get($publication, 'id'))
In Post\IndexController#duplicate we lose our $this data (empty).
We tried to get data like $this->enviroment but this variables are empty.
Anyone has any idea how to pass data with the variables filled by the middleware?
You can use the power of Container
Code in Controller.php
public function __construct()
{
$this->middleware(function ($request, $next) {
app()->instance('person', session()->get('person'));
app()->instance('environment', session()->get('environment'));
return $next($request);
});
}
In another controller:
<?php
namespace App\Http\Controllers;
class DupeController extends Controller
{
public function index()
{
dd(app('person'));
}
}
Just make sure if the "another controller" has it's own constructor, call the parent constructor, you your 'person' and 'environment' instance would be available in that controller.
<?php
namespace App\Http\Controllers;
class DupeController extends Controller
{
public function __construct()
{
parent::__construct();
// DO MAGIC
}
public function index()
{
dd(app('person'));
}
}
But I gotta tell you the truth, this is a bad practice. I just want to show you that something bad like this is possible. Try another approach like service injection to the controller using dependency injection technique and mark that service as a singleton, so container will resolve the same instance for every resolution (one instance per request).
Route::get('customer/{id}', 'Customer#method'); <-- want to call construct not method
class Customer extends Controller
{
public function __construct(){
echo 123456;
}
I'm new in laravel
I try to call __construct from my controller without method, but I got error, is anyone know how to do it?
Try to do like this
Define route
Route::resource('customer/{id}', 'Customer');
In your Customer Controller
use Route;
public function __construct()
{
$id = Route::current()->getParameter('id');
dd($id);
}
I'm new on laravel.
I have functions on my model php. I want to use them in controller and send to view.
This is my example function.
public function select()
{
$users = DB::table('garanti')->get();
}
now I need to use this on controller and view.
In codeigniter I handle it like this:
$data['kategori'] = $this->model->select_s();
$this->load->view('admin/kategori', $data);
If you do
class Post extends Eloquent {
public function select()
{
return DB::table('garanti')->get();
}
}
You can use it in your controller:
$data['kategori'] = with(new Post)->select();
return View::make('admin/kategori')->with('data', $data);
There are in fact other ways of doing this, but static functions are not really testable, so I wouldn't use them in this case.
This is a very good LIVE example about using MVC concept in Laravel. in this scenario the Controller is calling a function from the Model class then the Controller handle the view.Take a look.
http://runnable.com/UnFiFHVGrQh1AAA_/mvc-in-laravel-for-php
how to call model method in another model, example
I have code like this
/model/user.php
public function get_token_by_id($id){
//some code
}
i want call in my another model
/model/restaurant
App::bind('user','user');
class RestaurantController extends BaseController {
public function __construct(user $modelUser){
$this->modelUser = $modelUser;
}
public function getUser(){
$someVar = $this->modelUser->get_token_by_id($id);
}
}
But i get an error
Call to a member function get_token_by_id() on a non-object
how to fix it?
Well... that's because $this->modelUser is a non object !
To be more precise, $this->modelUser returns null or something like that (try a var_dump($this->modelUser)). It could be because your model doesn't have the attribute declaration (protected $modelUser) or because you don't pass the right variable into the constructor.