Laravel - Controller on Controller Dependecy - laravel

I have a Post model and a User model. Furthermore, I have a PostController and a UserController. Each post view has to be accompanied with its user view that displays the user information. Also, user has its own route and UserController allows each user view to be individually.
I would like to make it mandatory in my code to display the user view prior to calling the post view. In other words, PostController has a dependency on UserController. How can I achieve this?

You can achieve your goal in two ways.
First, you can use the view's include('view_file_name') to insert that view in the PostController's view. but then you have to initialise the variables in the PostController and pass it to the view.
Second, You can extends the UserController. if you wanted use the variables and functions of UserController in the PostController.
class PostController extends UserController {
}
Remember __construct of the UserController will be called when you call any function of PostController if you extends the controller.

Related

Laravel: When call function from another controller, the relationship query not work

I have two controllers (FirstController, SecondController) that use the same functions, to avoid rewriting them I thought of creating another controller (ThirdController) and subsequently calling the functions through it.
the problem is that if in ThirdController there are relationship query they give me the error that "they don't exist".
example:
User Model
class User extends Authenticatable implements AuthenticatableUserContract
{
use HasFactory, Notifiable;
public function comments(){
return $this->hasMany('App\Models\Comment');
}
ThirdController
class ThirdController extends Controller
{
public static function example($id){
$comments = Comment::find($id)->comments();
return $comments;
}
}
FirstController/SecondController
public function example2(Request $request){
return ThirdController::example($request->id);
When call the route it give me error:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::comments does not exist.
my questions are:
Is there any better method instead of creating a third controller?
Is there a solution to this?
p.s. I know I could very well build the queries without exploiting the relationship, but where's the beauty of that? :D
You do not need to create 3rd controller. You can create a class and here you write the query in a function and use this class in controller1 and controller2 by dependency injection.
First thing that's not a best practice to define a static method in one controller and call it in another controller (not recommended way).
Second you're calling Comment::find($id) with comments() relation. you should call a User class, like below snippet:
class ThirdController extends Controller
{
public static function example($id){
$comments = User::find($id)->comments();
return $comments;
}
}
RECOMEND APPROACH:
Creat a one seperate service/repository class in which you'll define a common method i.e. getUserComments() and use it in both or all of three controllers (upto your requirement/needs). By this way you implementations will be on a centric place.
If you want learn about Repository pattern you can get basic idea from: Article#1

Laravel - Share data with all views when the data is available

I'm writing a web app using Laravel 5.6. I need a list of all the connections the current session user have, in all the views.
I tried something like this
View::share('connections', Connection::getList(Auth::id()))
I put this code inside the boot function of AppServiceProvider. But the problem arises when the user isn't already logged in, because at that time Auth::id() is set to null.
The connection list is not generated when the user logs in. This throws the following error:
connections variable is not defined.
This target can achieve through different method,
1. Using BaseController
The way I like to set things up, I make a BaseController class that extends Laravel’s own Controller, and set up various global things there. All other controllers then extend from BaseController rather than Laravel’s Controller.
class BaseController extends Controller
{
public function __construct()
{
//its just a dummy data object.
$user = User::all();
// Sharing is caring
View::share('user', $user);
}
}
2. Using Filter
If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.
App::before(function($request)
{
// Set up global user object for views
View::share('user', User::all());
});
OR
You can define your own filter
Route::filter('user-filter', function() {
View::share('user', User::all());
});
and call it through simple filter calling.
Update According to Version 5.*
3. Using View Composer
View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.
View composer method can use different way, First example can look alike:
You could create an App\Http\ViewComposers directory.
Service Provider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
}
}
After that, add this provider to config/app.php under "providers" section.
TestViewComposer
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
class TestViewComposer {
public function compose(View $view) {
$view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
}
}
ViewName.blade.php
Here you are... {{$ViewComposerTestVariable}}
This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
public function boot() {
view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
}
}
Reference

As well to use controller inside another controller Laravel?

I have two entities: users, announcements
Eaach user can publish the announcements.
I creted controller AnnouncemetController, where there is method class: my(), that returns notes for current user.
Also I have controller ProfileController that represent current profile user, where I need to show all announcements of user.
For this I tried to reuse controller AnnouncemetController inside ProfileController and call public method my().
use App\Http\Controllers\AnnouncementController;
class ProfileController extends Controller
{
$my = new AnnouncementController();
$my->my();
}
Is it well to use such?
A Laravel controller maps a uri to an action. In your example, you are using a controller to access data, so this is not the "right thing to do".
Instead use model methods to access the data.

Create route for every controller of index method in Laravel

I'm developing a school management system in laravel. I have many controllers like
controller staff in method index
class controllerstaff extends controller {
public function index{
//here process of staff data
}
}
//this controller have `Route::get('/', 'controllerstaff#index');
and other controller
class controllerstudent extends controller {
public function index{
//here process of student data
}
}
//this controller have Route::get('/', 'controllerstudent#index');
As above does not work properly.
Any one can tell me how to create route for every controller of index method. If we crate many route file then how operate it and how access in controller and form action
You cannot create same urls for each route. For each route you need to have different url, for example:
Route::get('/staff', 'controllerstaff#index');
Route::get('/students', 'controllerstudent#index');
You should also name your controllers rather StudentController and not controllerstudent. You might also consider looking at Routing documentation before creating code - I believe it might be the right way ;)

What means the string Route::resource('user','UserController'); in laravel?

What means exactly the following strings in laravel?:
Route::resource('user','UserController');
I have the idea is system of routing for locate resources in laravel applications but what exactly mean every Word? Is the word 'user' an alias for UserController? since instead of 'user' can be used any other word
Route::resource is a way to specify several routes to your controller methods with a single declaration. For example, with Route::resource('user', 'UserController');, you can access index, update, create, show, store, edit and destroy methods in your UserController controller as shown below:
GET <url>/user //points to index() method on UserController
GET <url>/user/create //points to create() method on UserController
POST <url>/user //points to store() method on UserController
POST <url>/user/{userid}/edit //points to edit(userId) method on UserController
Source: Laravel Docs

Resources