I wish to initialize a particular variable and reuse it within the class without needing to rewrite the entire code again and again within the class.
$profileInfo = Profile::with('address')->where('id', '=', '1')->get();
The variable above is what I want to reuse.
I tried using constructor
protected $profileInfo;
public function __construct(Profile $profileInfo){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index($profileInfo){
$this->profileInfo;
dd($profileInfo);
}
But I get Too few arguments to function App\Http\Controllers\ProfileController::index(), 0 passed in the display when I load the blade view in the browser.
Please any help?
You're having trouble because you are mixing concepts. Dependency Injection, Local instance variables, and possibly route model binding or route variable binding.
Dependency Injection is asking Laravel to provide an instance of a class for you. In cases where Laravel is loading something, it typically tries to use DI to fill the unknowns. In the case of your constructor, you're asking Laravel to provide the constructor with a fresh instance of the Profile class under the variable name $profileInfo. You do not end up using this variable in the constructor, so there is no point to requesting it here.
Next (still in the constructor) you set up and assign the local variable profileInfo to the controller class instance.
Moving on, when the route tries to trigger the index method there is a variable requirement of $profileInfo. Laravel doesn't know what this is here and it doesn't match anything from the route (See Route Model Binding in the docs). Because of this you get the "Too few arguments" message.
If this variable was not present, you should have the profileInfo you set up earlier.
If you want to keep the local variable, you can do something like this:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
dd($this->profileInfo);
}
Here is another suggestion for you to consider...
Since this is called Profile, it seems like we should ask a user model for the appropriate profile record.
// in your user model, set up a relationship
public function profile(){
return $this->hasOne(Profile::class);
}
// In controller, if you're getting a profile for the logged in user
public function index(){
$profile = Auth::user()->profile;
dd($profile);
}
// In controller, if you're getting profile for another user via route model binding
public function index(User $user){
$profile = $user->profile;
dd($profile);
}
Related
I have a contact_info_scopes table and one of the scopes is 'Default', which is likely to be the most common scope called, so I'm creating an accessor
public function getDefaultScopeIdAttribute()
{
return $this::where('contact_info_scope', 'Default')
->first()
->contact_info_scope_uuid;
}
to get the defaultScopeId and wondering how I can new up the ContactInfoScope model and access that in one line. I know I can new it up:
$contactInfoScope = new ContactInfoScope();
and then access it:
$contactInfoScope->defaultScopeId;
but I would like to do this in one line without having to store the class in a variable. Open to any other creative ways of tackling this as well since an accessor may not really be ideal here! I'd be fine with just creating a public function (not as an accessor), but would have the same issue of calling that in one line. Thanks :)
You should be able to call the model and chain the value if you return the instance in its constructor method
(new ContactInfoScope)->defaultScopeID
Not tried it in Laravel but works in plain ol PHP
//LARAVEL
//write on model ----------------------------------
protected $appends = ['image'];
public function getImageAttribute()
{
$this->school_iMage = \DB::table('school_profiles')->where('user_id',$this->id)->first();
$this->studend_iMage = \DB::table('student_admissions')->where('user_id',$this->id)->first();
return $this;
}
//call form anywhere blade and controller just like---------------------------
auth()->user()->image->school_iMage->cover_image;
or
User::find(1)->image->school_iMage->cover_image;
or
Auth::user()->image->school_iMage->cover_image;
// you can test
dd( User::find(1)->image);
I am newbie with Laravel. I have just fork laravel 5 boilerplate from https://github.com/rappasoft/laravel-5-boilerplate.
In route files, i see that there is a line like that :
Route::group(['prefix' => 'user/{deletedUser}'], function () {
Route::get('delete', 'UserStatusController#delete')->name('user.delete-permanently');
Route::get('restore', 'UserStatusController#restore')->name('user.restore');
});
I understand it means that, when url catch 'restore' it will use function restore in UserStatusController.
And here it is:
public function restore(User $deletedUser, ManageUserRequest $request)
Can anybody can help me to find out that, how can it send object $deletedUser to restore function. Tks you!
If your look at the route definition:
user/{deletedUser}
That {deletedUser} represents the id of the user to be deleted/restored. Variables are declared between {} in routes as the docs states.
Now in your controller:
public function restore(User $deletedUser, ManageUserRequest $request)
You can see that a User object is declared as an argument. This object is being injected by Laravel, that automatically will look for an User object that has that id. This is called Route Model Binding.
The documentation explains it better:
When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.
The same way, the Request class injected in this case is a ManageUserRequest that should be an instance of a FormRequest.
So, returning to your question, you will just have to specify the user id that you want to delete/restore, like this:
someurl.dev/users/5 // <-- for the user of id=5
Now your controller will interact with that specific object to do what you want:
public function restore(User $deletedUser, ManageUserRequest $request)
{
$deletedUser->delete(); // for example
}
There are two things happening here: parameters (docs) and model binding (docs)
First of all, in ['prefix' => 'user/{deletedUser}'] you can see that you are parsing a parameter from the url. This way, when someone navigates to api/user/3, laravel will pass the 3 to your route handler.
Second, it would be very nice to get the User model instance instead of just getting an id number. That's possible and it's called "model binding". Model binding can be
Explicit
You add your bindings to boot method in your RouteServiceProvider class, telling laravel what is the expected type of parameter.
public function boot()
{
parent::boot();
Route::model('deletedUser', App\User::class);
// in older docs I've seen 'App\User' passed as a string instead of as a class
}
Implicit
Laravel automatically figures out what model you need based on type hints.
public function restore(User $deletedUser, ManageUserRequest $request) {}
Here, $deletedUser has is type hinted as User. Laravel sees this, so it will go ahead and convert the id to the Eloquent model for you.
You seem to be using implicit binding, but feel free to check your RouteServiceProvider class.
Check the documentation links for more details, it's pretty well written. (If you are not using version 5.6, then just change the version number in the links).
You Just need to pass ID of the user as a parameter.
And this function
public function restore(User $deletedUser, ManageUserRequest $request)
you can see $deletedUser is of type User Laravel will search for that id ($deletedUser) in Users table and return an object of that user.
If you don't want User object and just need ID that you are passing in URL update restore() function to
public function restore($deletedUser, ManageUserRequest $request)
I am building an application with multiple user roles and actions. I did follow the official laravel doc (https://laravel.com/docs/5.5/middleware#middleware-parameters).
But in my controller's constructor (from where I call the above middleware) I am using Auth facade to get user details. I know how to use Auth facade, I had implemented it on several places inside my application. But when I use it inside the constructor it returns null (in logged in condition - I double checked that).
I implemented it like this, I have to call two controllers(since only registered users can access that page)
public function __construct()
{
$role = Auth::user()->role;
$this->middleware('auth');
$this->middleware('checkRole:$role');
}
PS: I tried to initialize $role variable as protected and outside the constructor , still not working. Any suggestions will be helpful
Thank you.
That's because constructors are created before middlewares,that's why its returning null.
This answer will propably solve your problems: Can't call Auth::user() on controller's constructor
If you are using the same user table for both "front-end" user and "admin" & want to apply condition in admin controller's constructor.
You can use below.
auth()->user()
And in the constructor you can use below code.
public function __construct(){
$this->middleware(function ($request, $next) {
if(auth()->user()->hasRole('frontuser')){
return redirect()->route('home')->withFlashMessage('You are not authorized to access that page.')->withFlashType('warning');
}
return $next($request);
});
}
But I prefer to handle these in separate middleware class instead of writing this in the controllers constructor.
What I wanna do is to know, inside a view, if I'm in a specific controller or not. From what I know, I've got two choices and I don't have the answer to either of them :-D
inject a view variable using the share method in my AppServiceProvider, which involves getting the current controller name(or at least the action name so that I can switch it) inside the service provider.
inject a variable to all the views returned in the controller. For example does controllers have a boot method? Or can I override the view() method in the following code snippet?
public function someAction(Request $request)
{
return view('someview', ['myvar' => $myvalue]);
}
well of course there's the easy (yet not easy :|) solution: add the variable in all methods of the controller. I don't like this one.
Thanks
You could use the controller's construct function.
Add this to the top of your controller:
public function __construct()
{
view()->share('key', 'value');
}
Is there any easy way of retrieving the route binded model within a Request?
I want to update a model, but before I do, I want to perform some permissions checks using the Requests authorize() method. But I only want the owner of the model to be able to update it.
In the controller, I would simply do something like this:
public function update(Request $request, Booking $booking)
{
if($booking->owner->user_id === Auth::user()->user_id)
{
// Continue to update
}
}
But I'm looking to do this within the Request, rather than within the controller. If I do:
dd(Illuminate\Http\Request::all());
It only gives me the scalar form properties (such as _method and so on, but not the model).
Question
If I bind a model to a route, how can I retrieve that model from within a Request?
Many thanks in advance.
Absolutely! It’s an approach I even use myself.
You can get the current route in the request, and then any parameters, like so:
class UpdateRequest extends Request
{
public function authorize()
{
// Get bound Booking model from route
$booking = $this->route('booking');
// Check owner is the currently authenticated user
return $booking->owner->is($this->user());
}
}
Unlike smartman’s (now deleted) answer, this doesn’t incur another find query if you have already retrieved the model via route–model binding.
However, I’d also personally use a policy here instead of putting authorisation checks in form requests.
Once you did your explicit binding (https://laravel.com/docs/5.5/routing#route-model-binding) you actually can get your model directly with $this.
class UpdateRequest extends Request
{
public function authorize()
{
return $this->booking->owner->user_id == $this->booking->user()->id;
}
}
Even cleaner!
To add on to Martin Bean's answer, you can access the bound instance using just route($param):
class UpdateRequest extends Request
{
public function authorize()
{
$booking = $this->route('booking');
return $booking->owner->user_id == $this->user()->id;
}
}
Note: This works in Laravel 5.1. I have not tested this on older versions.
If you are not using the bindings middleware or if you want to access the bound $model anywhere else apart from FormRequest and Controller you can use the following:
$book = app(Book::class)->resolveRouteBinding(request()->route('book'));