How to access method in eloquent model of current user - php

Everything what I was searching tells me about Auth::user() or auth()->user() but it gives access to result of query to DB - to all fields of record.
Here are details.
Laravel 8.x
There is eloquent model called User. I created also another elo model Example. There is relation in database one-to-one so table examples has foreign key user_id. In User model I created
public function example() { return $this->hasOne(); }
and in Example:
public function user() { $this->belongsTo(); }
Now I have ExampleController with public function __contruct() - if current user doesnt have related example yet I want to run view to create it.
Tell me please what is a correct way to do that - to access current user model method?

You could use an inline middleware
use App\Models\Example;
use Illuminate\Support\Facades\Auth;
class ExampleController extends Controller
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if ( Example::where('user_id', Auth::id())->doesntExist() ) {
return redirect('user-has-no-example');
}
return $next($request);
});
}
}

Related

Get the morphMany relationship to a model from the user

Let say i have the following;
User Model;
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('App\Models\Socials\Post');
}
}
Post Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany('App\Models\Socials\Comment', 'commentable');
}
Comment model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
When i used $user = User::find($id); and $user->posts(), it returns all the post of the user, but if i used this method $user->posts()->comments() It return this message Method Illuminate\Database\Query\Builder::comments does not exist.
The question is how can i get all the comments of the user on the said post?
Change:
$user->posts()->comments();
to:
$user->posts->pluck('comments')->collapse();
The method itself returns an instance of Eloquent's query builder allowing you to add to or edit the query if you want. However, if you don't want to edit the query you can access the relationships as properties and Laravel will handle to execution of the query.
Essentially, $user->posts is actually turning into $user->posts()->get() in the background.
Credit to #JonasStaudenmeir.

Laravel - Access The Authenticated User In A Model Observer

I followed the documentation for creating a model observer here https://laravel.com/docs/5.5/eloquent#observers.
But when I try and access the authenticated user I get null.
How can I access the authenticated user in the model observer?
<?php
namespace App\Observers;
use App\Customer;
class CustomerObserver
{
public function created(Customer $customer)
{
dd(auth()->user());
}
public function updated(Customer $customer)
{
dd(auth()->user());
}
}
I've also tried this inside the Customer model and it returns null as well.
public static function boot()
{
parent::boot();
self::updated(function ($model) {
dd(auth()->user());
});
}
Ok, so stupid mistake on my end.
Thanks #fubar for the tip.
I was using a custom authentication provider so I needed to do this:
dd(auth()->guard('admin')->user());

how to get all rows where specific column = id of other row in different table

I am trying to get all rows in a payments table where I have another table called projects I want to get all rows that in payments table where project_id column = ID of the row inside projects table I am using Laravel framework please help me this some the code
Payment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $table = 'payments';
public function projects() {
return $this->belongsTo('App\Project');
}
}
Project Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = "projects";
public function payments() {
return $this->hasMany('App\Payment');
}
}
Route File
Route::get('special/{project_id}', 'SpecialController#index');
The index function in the Controller
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Payment;
use Illuminate\Http\Request;
class SpecialController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Project $project_id)
{
return view('special.index')->with(['projects' => $project_id]);
}
This is my problem please help
All the best 😀
In your controller, I see that u have injected an instance if Project, but named as $project_id. Thats not an id, id would have been resolved to an instance of Project.
public function index(Project $project_id)
just a note. use index method to show the listing, unless its a nested resource.
public function index(Project $project)
{
//assuming that $project is an instance of Project
$project = $project->with('payments')->get();
//$project will now include the related payments as well
//if you want to check do this, for debugging uncomment next line
//dd($project->toArray());
return view('special.index')->with(['project' => $project]);
}
whats happening in code is that $project is retrieved with its related payments. in with('payments') the 'payments' is the name of the relationship.

Get the bound route model instance in a generic parent class

I'm using Laravel 5.1's route model binding to infer/instantiate the correct model instance from the routes.
I don't want to rewrite a show() method for each resource, and would rather call parent show() method in a generic parent class. The problem is, I don't know how to allow my parent class's show() method to infer the correct model instance, so I'm forced to create a show() on each child resource and specify the model (like below, User $user).
How can I get the bound model in my controllers from the binding in RouteServiceProvider: App\User? And pass it through to the parent show() method?
Route:
// Passing in id 1 for {user}
$router->get('/users/{user}', 'Resources\Users#show');
RouteServiceProvider.php:
public function boot(Router $router)
{
parent::boot($router);
$router->model('user', 'App\User');
}
UsersController.php: How I am currently doing it
class User extends ResourceController
{
public function show(Request $request, User $user)
{
// Returns user of ID 1 as expected
return $user;
}
ResourceController.php: How I'd like to do it
class ResourceController extends Controller
{
public function show(Request $request, Model $model)
{
// Infer "Users" model here and returns User with ID 1
return $model;
}

Laravel 4 Injecting an Eloquent Model in a controller

I am new to this concept of DI, and IoC so i might be doing this completely wrong but i am trying to inject the Model that matches a controller into that controllers constructor (UserModel -> UsersController) so that i can mock it later on.
So my model looks like:
use Illuminate\Auth\UserInterface;
class User extends Eloquent implements UserInterface {
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
}
And i am then trying to inject in UsersController like so :
class UsersController extends Controller {
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function index()
{
//dd( $this->user);
$users = $this->user->all();
foreach ( $users as $user )
print_r($user);
return;
}
}
Then when i hit this controller in the browser i get a "Unresolvable dependency resolving" error.
I noticed that this happend only when the class that i am trying to inject is a sub class of eloquent, if i try the same code with a custom class that do not extend eloquent then it works fine.
Am i missing something?
Further to the comments, I finally got to know that this is a complicated issue. To bypass this you need to bind your model with the IoC and return a new instance of your model manually.
App::bind('User', function()
{
return new User;
});

Categories