Laravel Models/function, how to make a main "function" - laravel

So guy's, I've created a Laravel project.
I have a master. Layout which always contains the user data.
So I have a navbar with $user->name for example.
In every controller I needed to add the User model and also the where function.
$user = User::find(auth()->user()->id)
Maybe this example is bad, but I've also included the company in the master, so it shows in the Navbar.
Is there a way, that I don't need to repeat that process? So I don't need it always in the controller.
Thanks for reading.

In laravel you are extending each class from a main controller so its better to create a method in main class like this
child controller
class testController extends Controller
{
// as you can see its extending so go into Controller class
}
parent class, So here i have creatd a getName method here. If you want get the value through mode
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private $current_user_name = 'test';
public function getName()
{
return ($this->current_user_name);
}
}
Now go back to child controller and pass this method in view
class testController extends Controller
{
public function index()
{
return view('', $data = ['name' => $this->getName()]);
}
}
Hope this cover your query. In this way you don't need to repeat your code in every controller.

You can get data in your blade template too, like user information, but if you need more complex data and you don't want to put logic in blade, you can use this method (AppServiceProvider.php):
public function boot()
{
view()->composer('your_mast_layout', function($view)
{
$data = ...
$view->with('variable_name', $data);
});
}

Related

How to mock laravel model relathipship?

I have a model that has a relationship with a View, that is complicate to popolate for make the feature test, but in the same time this is called from some component that are inside the controller called.
The following code is an example:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\TemperatureView;
class Town extends Model
{
function temperature()
{
return $this->hasOne(TemperatureView::class);
}
}
This is an example of the controller:
<?php
namespace App\Http\Controllers;
use App\Models\Town;
class TownController extends Controller
{
public function update($id)
{
// Here is the validation and update of Town model
$UpdatedTown = Town::where('id',$id);
$UpdatedTown->update($data);
$this->someOperation($UpdatedTown);
}
private function someOperation($Town)
{
//Here there is some operation that use the temperature Relationship
/*
Example:
$Town->temperature->value;
*/
}
}
The test is like is like this:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
use App\Models\TownModel;
use Mockery;
use Mockery\MockInterface;
class TownTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function test_get_town_temperature()
{
$payload = ['someTownInformation' => 'Value'];
$response = $this->post('/Town/'.$idTown,$payload);
$response->assertStatus(200);
//This test failed
}
public function test_get_town_temperature_with_mocking()
{
$this->instance(
TownModel::class,
Mockery::mock(TownModel::class, function (MockInterface $mock) {
$MockDataTemperature = (object) array('value'=>2);
$mock->shouldReceive('temperature')->andReturn($MockDataTemperature);
})
);
$payload = ['someTownInformation' => 'Value'];
$response = $this->post('/Town/'.$idTown,$payload);
$response->assertStatus(200);
//This test also failed
}
}
The first test failed because the Controller has some check on the relationship temperature, that is empty because the view on database is empty.
The second test failed also for the same reason. I tried to follow some others questions with the official guide of Laravel Mocking. I know this is mocking object and not specially Eloquent.
Is something I'm not setting well?
If it's not possible to mock only the function, is possible to mock all the relationship of view, bypassing the DB access to that?
Edit
I undestand that the mocking work only when the class is injected from laravel, so what I wrote above it's not pratical.
I don't know if it's possible to mock only it, I saw a different option, that to create the interface of the model and change for the test, but I didn't want to make it.

Laravel 5.8 add data to a layout variable via controller constructor

I am trying to add data to a layout variable via a controller constructor. The reason I want to do this is because I always need to add categories to the topmenu when this controller is called.
No success so far. I add data to a layout via a view composer like this.
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Menu;
class MenuComposer
{
public function compose(View $view)
{
if (in_array($view->getName(), ['layouts.master', 'layouts.master-post', 'layouts.error']))
{
$menu = Menu::menu('topmenu');
view()->with('topmenu', $menu);
// view()->share('topmenu', $menu); not working either
}
}
}
I want to extend the data in a Controller constructor.
namespace App\Http\Controllers\Post;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\View\View;
class PostController extends Controller {
public function __construct(View $view)
{
$view->offsetGet('topmenu');
// $view->gatherData() not working either
}
Whatever I try, Laravel throws an exception:
Target [Illuminate\Contracts\View\Engine] is not instantiable while building [App\Http\Controllers\Post\PostController, Illuminate\View\View].
What I did in the serviceprovider boot function:
view()->share('topmenu', [
'items' => $newItemsToAdd
]);
In the viewComposer I did:
$extraItems = view()->shared('topmenu');
if (!empty($extraItems)) {
$items = aray_merge($items, $extraItems);
}
}

Laravel blade file can't view

I created CustomerController in Http, later, I fixed-route get customers, but getting an error in a single action Controller.
I tried to show off CustomerController view for displaying customers logged in page
Here is my error message:
Use of undefined constant view - assumed 'view' (this will throw an Error in a future version of PHP)
Looks like you're trying to access the old ways to render blade file look at this :-
return View::make('customers.index', $customersList);
To use view() method
return view('admin.pages.customers.index',compact('someVaiable'));
OR
// You can define constant for your controller get methods
private $layout;
public function __construct()
{
$this->layout = 'admin.pages.customers.';
}
public function index(){
return view($this->layout.'index');
}
Take a look a this for Single Action Controllers example
https://laravel.com/docs/5.8/controllers#single-action-controllers
The first argument of the view method in the controller should be the name of the view.
Routes/web.php
Route::get('/', 'CustomerController');
app/Http/Controllers/CustomerController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CustomerController extends Controller
{
public function __invoke(Request $request)
{
return view('customers');
}
}
resources/views/customers.blade.php
<h1>Customers</h1>

Dynamically hide Laravel barryvdh debugbar

I could not able to hide Laravel Debugbar dynamically, i.e on the run time. I have tried the following from parent Controller class constructor:
<?php
namespace App\Http\Controllers;
class Controller extends BaseController {
use AuthorizesRequests,
DispatchesJobs,
ValidatesRequests;
public $foo = 'null';
public function __construct() {
\Debugbar::disable();
// and also
config(['debugbar.enabled' => false]);
....
All of the above tries failed. I'd like to mention that controller is the parent controller of all other controllers' classes.
The only working way is not dynamic way, where I have to change configuration manually. I don't know why the override configurations doesn work as the documentation states?
Without seeing all you code, yours should work. Here is how I configure mine to work in a local environment and disable it with specific requests.
AppServiceProvider
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
...
public function register()
{
if ($this->app->environment('local')) {
$this->app->register(DebugbarServiceProvider::class);
}
}
Where I would like to disable I put.
use Barryvdh\Debugbar\Facade as Debugbar;
...
if (App::environment('local')) {
Debugbar::disable();
}
Update per comment
Why do you put something in your routes file like this.
use Barryvdh\Debugbar\Facade as Debugbar;
...
Route::group(array('domain' => 'admin.example.com'), function()
{
Debugbar::disable();
});

How can i get result from model in laravel 5

Good day, i'm trying to get the result from my model that called with Mainmodel through my controller, my controller is MainController.
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Mainmodel;
class MainController extends Controller
{
function index(){
echo "Kok, direct akses sih?";
}
function get_menu(){
$menu = app\Mainmodel::request_menu();
dd($menu);
}
}
Here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mainmodel extends Model
{
function request_menu(){
$menu = DB::table('menu')
->orderBy('[order]', 'desc')
->get();
return $menu;
}
}
my routes
Route::get('menu','MainController#get_menu');
with my script above i get this
FatalErrorException in MainController.php line 17: Class
'App\Http\Controllers\app\Mainmodel' not found
how can i fix this ? thanks in advance.
Note: I'm bit confuse with laravel. I'm using codeigniter before. And i have a simple question. In laravel for request to database should i use model ? or can i just use my controller for my request to database.
sorry for my bad english.
I would imagine it's because your using app rather than App for the namespace.
Try changing:
app\Mainmodel
To:
App\Mainmodel
Alternatively, you can add a use statement to the top of the class and then just reference the class i.e.:
use App\Mainmodel;
Then you can just do something like:
Mainmodel::request_menu();
The way you're currently using you models is not the way Eloquent should be used. As I mentioned in my comment you should create a model for each table in your database (or at least for the majority of use cases).
To do this run:
php artisan make:model Menu
Then in the newly created Menu model add:
protected $table = 'menu';
This is because Laravel's default naming convention is singular for the class name and plural for the table name. Since your table name is menu and not menus you just need to tell Laravel to use a different table name.
Then your controller would look something like:
<?php
namespace App\Http\Controllers;
use App\Menu;
class MainController extends Controller
{
public function index()
{
echo "Kok, direct akses sih?";
}
public function get_menu()
{
$menu = Menu::orderBy('order', 'desc')->get();
dd($menu);
}
}
Hope this helps!
You can solve it by different solution. The solution is you don't have to call request_menu(); you can get it in your controller.
MainController
use use Illuminate\Support\Facades\DB;
public function get_menu(){
$menu = DB::table('menu')
->orderBy('Your_Field_Name', 'DESC')
->get();
dd($menu);
}

Resources