Laravel : send pivot tables data in view - php

I'm new to Laravel 5 and I have some difficulties with pivot tables, controllers and repositories.
I have the tables 'users', 'sites', 'site_user', and here is what I have now :
App\Models\User
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
protected $table = 'users';
public function sites()
{
return $this->belongsToMany('App\Models\Site')
->withPivot('site_id', 'user_id', 'relation');
}
}
App\Models\Site
class Site extends Model {
protected $table = 'sites';
public function user()
{
return $this->belongsToMany('App\Models\User')
->withPivot('site_id', 'user_id', 'relation');
}
}
App\Repositories\SiteRepository
<?php namespace App\Repositories;
use App\Models\Site, App\Models\User;
class SiteRepository extends BaseRepository
{
/**
* The User instance.
*
* #var App\Models\User
*/
protected $user;
/**
* Create a new SiteRepository instance.
*
* #param App\Models\Site $site
* #return void
*/
public function __construct (Site $sites, User $user)
{
$this->model = $sites;
$this->user = $user;
}
/**
* Get sites collection paginate.
*
* #param int $n
* #return Illuminate\Support\Collection
*/
public function index($n)
{
return $this->model
->latest()
->paginate($n);
}
App\Http\Controllers\SiteController
<?php namespace App\Http\Controllers;
use App\Repositories\SiteRepository;
use App\Repositories\UserRepository;
use App\Http\Requests\SiteCreateRequest;
use App\Http\Requests\SiteUpdateRequest;
use App\Models\Site;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SiteController extends Controller {
/**
* The SiteRepository instance.
*
* #var App\Repositories\SiteRepository
*/
protected $site_gestion;
/**
* The UserRepository instance.
*
* #var App\Repositories\UserRepository
*/
protected $user_gestion;
/**
* Create a new SiteController instance.
*
* #param App\Repositories\SiteRepository $site_gestion
* #param App\Repositories\UserRepository $user_gestion
* #return void
*/
public function __construct (SiteRepository $site_gestion, UserRepository $user_gestion)
{
$this->site_gestion = $site_gestion;
$this->user_gestion = $user_gestion;
$this->middleware('admin');
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(SiteRepository $site_gestion)
{
//$counts = $this->site_gestion->counts();
$sites = $site_gestion->index(25);
$links = $sites->render();
return view('back.sites.index', compact('sites'));
}
views\back\sites\table.blade.php
#foreach ($sites as $site)
[...some code...]
#endforeach
What I want to do is to get all the sites of the logged in user. I've tried many things, but none of them are working. And I'm still not sure where to put the code, repository or controller...
I've read tutorials about pivot in Laravel, and I've tried with some things like this in the repo, but it doesn't work...
$user = $this->user->find(auth()->user()->id); //This line is working
foreach ($user->sites as $site) {
return $site
->latest()
->paginate($n);
}

If you want all sites of a logged user simply do it like this:
$sites = Auth::user()->sites;
That's all you need to do to get to these sites. If you want to use query and pagination try like this:
$sites = Auth::user()->sites()->latest()->paginate($n);

So what you've done seems pretty close.
So you pretty much have it, when iterating over the sites they should be instances of the site model.
$user = auth()->user(); // This is a way of saying your first line without a db query for the user
foreach ($user->sites as $site) {
// each site in here is a site model
$site->pivot->relation;
}
The only other thing that looks slightly strange is how you've defined the pivots. Generally when calling withPivot you wouldn't define the joining ids, if you wish to vary from the defaults you can pass it as an argument to the belongsToMany like so.
return $this->belongsToMany('App\Models\User', 'site_user', 'user_id', 'site_id')
->withPivot('relation');

Related

Laravel How to Test Static Query Builder Methods?

I have the following single responsibility repository class
<?php
namespace App\Launches\Repositories\Customer;
use App\Launches\Models\Customer\Subscription;
use Illuminate\Support\Collection;
final class GetSubscriptionRepository
{
/**
* #param int $productId
* #return Collection
*/
public function byProductId(int $productId): Collection
{
return Subscription::where('product_id', $productId)->get();
}
}
I want to be able to test that method, to make sure the object retrieve is the one I've asked. So I've done the following:
<?php
namespace Tests\Unit\Launches\Repository\Customer;
use App\Launches\Models\Customer\Subscription;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Collection;
use Tests\TestCase;
use App\Launches\Repositories\Customer\GetSubscriptionRepository;
class GetSubscriptionRepositoryTest extends TestCase
{
use RefreshDatabase;
/**
* #var GetSubscriptionRepository
*/
protected $getSubscriptionRepository;
/**
* #var Collection
*/
protected $subscriptionCollection;
public function setUp(): void
{
parent::setUp();
$this->getSubscriptionRepository = new GetSubscriptionRepository();
$this->subscriptionCollection = factory(Subscription::class, 20)->make();
}
/**
* #covers GetSubscriptionRepository::byProductId
*/
public function testSubscriptionIsPickedById()
{
$randomSubscription = $this->subscriptionCollection->random(1)->first()->toArray();
$pickedSubscription = $this->getSubscriptionRepository->byProductId($randomSubscription['id']);
$this->assertEquals($randomSubscription['id'], $pickedSubscription->get('id'));
}
}
It's always returning null on $this->getSubscriptionRepository->byProductId($randomSubscription['id']);
It is obviously expecting stuff to be in the database, is there a way to test it without adding stuff to the database?

how to access relationship and pass into a view in laravel

a beginner question here, how can i get the building_name column on my buildings table which has a relationship with information, i wanted to access it inside the show function and display in on the show.views? And i also wanted to know how can i call it inside the show view Please help.
<?php
namespace App\Http\Controllers;
use App\Information;
use App\Building;
use Illuminate\Http\Request;
use Session;
class InformationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$buildings = new Building();
$buildings::all();
return view('create', compact('buildings'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, array(
'building_information' => 'required',
'building_id' => 'required'
));
//store in the db
$information = new Information;
$information->building_information = $request->building_information;
$information->building_id = $request->building_id;
$information->save();
Session::flash('success', 'The information was successfully saved!');
//redirect to other page
return redirect()->route('information.show', $information->id);
}
/**
* Display the specified resource.
*
* #param \App\Information $information
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$information = Information::find($id);
return view('show')->with('information', $infomation);
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
public function information()
{
return $this->hasMany('App\Information');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Information extends Model
{
public function building()
{
return $this->belongsTo('App\Building');
}
}
Load the relationship too when getting the Information object:
$information = Information::with('building')->find($id);
If there are multiple buildings associated, you can loop through them in your blade view:
#foreach( $information->building as $building)
<li>{{ $building->building_name }}</li>
#endforeach
Just add relationship and pass it to the view
public function show($id)
{
$information = Information::with('building')->findOrFail($id);
return view('show')->with('information', $infomation);
}
In your view:
{{$information->building->building_name}}

Extending model class causes Column not found error

I'm using https://github.com/spatie/laravel-permission
I have created a new class which extends the Role class. Here is the code for Role:
<?php
namespace Spatie\Permission\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Contracts\Role as RoleContract;
use Spatie\Permission\Traits\RefreshesPermissionCache;
class Role extends Model implements RoleContract
{
use HasPermissions;
use RefreshesPermissionCache;
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
public $guarded = ['id'];
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->setTable(config('laravel-permission.table_names.roles'));
}
/**
* A role may be given various permissions.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function permissions()
{
return $this->belongsToMany(
config('laravel-permission.models.permission'),
config('laravel-permission.table_names.role_has_permissions')
);
}
/**
* A role may be assigned to various users.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(
config('auth.model') ?: config('auth.providers.users.model'),
config('laravel-permission.table_names.user_has_roles')
);
}
/**
* Find a role by its name.
*
* #param string $name
*
* #throws RoleDoesNotExist
*
* #return Role
*/
public static function findByName($name)
{
$role = static::where('name', $name)->first();
if (! $role) {
throw new RoleDoesNotExist();
}
return $role;
}
/**
* Determine if the user may perform the given permission.
*
* #param string|Permission $permission
*
* #return bool
*/
public function hasPermissionTo($permission)
{
if (is_string($permission)) {
$permission = app(Permission::class)->findByName($permission);
}
return $this->permissions->contains('id', $permission->id);
}
}
My code was working fine when accessing this Role class directly for create()'s, but attempting to perform the same tasks using my new UserRole class, I am getting Column not found database errors when attempting to create a new Role.
Here is the UserRole class:
namespace App;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Models\Role;
class UserRole extends Role
{
use LogsActivity;
/**
* The attributes that should be logged.
*
* #var array
*/
protected static $logAttributes = ['name', 'permissions'];
}
So Role::create() works fine, but UserRole::create() does not.
Well changing the name to Role and then changing my use clause to as SpatieRole has fixed the issue. I'm guessing it was some type of class name relationship issue with Eloquent.
If you don't define the $table property on your Eloquent model, the table name is derived from the name of the Model. So, the Role model would use the roles table by default. The UserRole model would look for the user_roles table by default.
Since you still want to use the same table, but your model name is changed, you will need to define the $table property on your new model to make it look at the roles table.
class UserRole extends Role
{
protected $table = 'roles';
// ...
}

ViewComposer Doesn't Work

I have made a header.blade.php which is extended to many View pages. in header menu items come from database.So I used ViewComposer.
Here is my ComposerServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(['cart.layouts.header'], 'App\Http\ViewComposers\CategoryComposer#compose');
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
here is the CategoryComposer Class:
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
class CategoryComposer
{
public $categoryList = [];
/**
* Create a movie composer.
*
* #return void
*/
public function __construct()
{
$this->categoryList = \DB::table('categories')
->select('categories.*')
->get();
}
/**
* Bind data to the view.
*
* #param View $view
* #return void
*/
public function compose(View $view)
{
$view->with('categories', end($this->categoryList));
}
}
I have also registered the Service Provider in config/app
But the problem is I got error in other pages like Undefined variable: categories
Can you suggest me what could be the Error here?

How do I solve "Target [Interface] is not instantiable" in Laravel 4?

My error message:
Illuminate \ Container \ BindingResolutionException
Target [Project\Backend\Service\Validation\ValidableInterface] is not instantiable.
I understand that interfaces and abstract classes are not instantiable so I know that Laravel should not be trying to instantiate my interface. Yet somehow it's trying to and I suspect this may be a binding issue...even though I believe I have bound it correctly and have registered it as a service provider.
I should mention that I have taken this example out of Chris Fidao's "Implementing Laravel" and it's almost identical!
This is the first couple of lines of my form class:
namespace Project\Backend\Service\Form\Job;
use Project\Backend\Service\Validation\ValidableInterface;
use Project\Backend\Repo\Job\JobInterface;
class JobForm {
/**
* Form Data
*
* #var array
*/
protected $data;
/**
* Validator
*
* #var \Project\Backend\Form\Service\ValidableInterface
*/
protected $validator;
/**
* Job repository
*
* #var \Project\Backend\Repo\Job\JobInterface
*/
protected $job;
public function __construct(ValidableInterface $validator, JobInterface $job)
{
$this->validator = $validator;
$this->job = $job;
}
This is the first few lines of my validator class:
namespace Project\Backend\Service\Form\Job;
use Project\Backend\Service\Validation\AbstractLaravelValidator;
class JobFormValidator extends AbstractLaravelValidator {
// Includes some validation rules
This is the abstract validator:
namespace Project\Backend\Service\Validation;
use Illuminate\Validation\Factory;
abstract class AbstractLaravelValidator implements ValidableInterface {
/**
* Validator
*
* #var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Validation data key => value array
*
* #var Array
*/
protected $data = array();
/**
* Validation errors
*
* #var Array
*/
protected $errors = array();
/**
* Validation rules
*
* #var Array
*/
protected $rules = array();
/**
* Custom validation messages
*
* #var Array
*/
protected $messages = array();
public function __construct(Factory $validator)
{
$this->validator = $validator;
}
This is the code where I bind it all to the app:
namespace Project\Backend\Service\Validation;
use Illuminate\Support\ServiceProvider;
use Project\Backend\Service\Form\Job\JobFormValidator;
class ValidationServiceProvider extends ServiceProvider {
public function register()
{
$app = $this->app;
$app->bind('Project\Backend\Service\Form\Job\JobFormValidator', function($app)
{
return new JobFormValidator($app['validator']);
});
}
}
This is then registered in app/config/app.php:
.....
'Project\Backend\Service\Validation\ValidationServiceProvider',
....
Finally these are the first few lines of my controller:
use Project\Backend\Repo\Job\JobInterface;
use Project\Backend\Service\Form\Job\JobForm;
class JobController extends \BaseController {
protected $jobform;
function __construct(JobInterface $job, JobForm $jobform)
{
$this->job = $job;
$this->jobform = $jobform;
}
You need to tell Laravel which instance it should use for a certain interface when injecting it into the constructor via type hinting.
You do this using the bind() method (in your service provider for example)
$app->bind('JobInterface', 'Job'); // Job being the class you want to be used
I highly recommend you watch the video here where Taylor Otwell, the creator of Laravel, explains this and some other things.
First you need to bind using
/app/Providers/AppServiceProvider.php
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
$this->app->bind('JobInterface', 'Job');
}
}
Once you complete this change
Run composer update

Categories