In Laravel Can I create a new Model Instance without new? - php

For example:
You can create a new model instance of User as:
new App\Model\User()
But when I use it in blade views, looks like:
new App\Model\User()->..->...
I think it is not a good way. It's not so elegant.
So I want to add some methods to achieve that I can use like below in blade views:
User::instance()->..->...
How can I achieve this? Thanks a lot!
Thanks for helping. I know it is not a good way to call model in blade views. But in some cases, sometimes I still have chance calling model in blade views for convenient.
For example, in create blade form, usually use like this:
{!!Form::model(new App\Model\User, ['url' => '/', 'class' => 'form' ])!!}
So there is chance to use model in blade views. So I want to find a elegant way to get an instance of Model instead of using new App\Model\ModelName...
Like
User::instance()
to get a new instance of \App\Model\User.
Can scopeQuery in model works?

First of all, if you understand the concept of MVC you should know the relationship between a model, view and controller.
The controller as a middle man should do the work of passing appropriate data to your view.
This is a better way to do it in Laravel.
Your controller:
use App\Model\User;
class AccountController extends Controller{
public function __construct (User $user){
$this->user = $user;
}
public function profile(){
return view('profile, ['user'=>$this->user]);
}
}
Then in your view, profile.blade.php
Welcome {{$user->name}}

Related

Laravel , how to call a function from another controller

I have a controller with the "getUsers" function in a controller called "UserController" , and inside it I want to call a function of the "CarController" controller called "getCars", the two options I have are:
a) Make the second call as "static" , then I can call it without instantiating the class
b) Do not do that function of the static class and I call it in this way
$ car_id = 100;
$ userController = new UserController ();
$ userController-> getCars ($ car_id);
I do not know which is the best practice, or what pros or cons has one or another.
I'm using laravel.
Thanxs.
It is a bad practice to call a controller from another controller, this usually signals that you have badly designed your code and you should think of a different way to achieve what you want.
None the less, you can do it like this:
app()->call('App\Http\Controllers\CarController#getCars');
If your controller method has parameters you can pass them as the second argument:
app()->call('App\Http\Controllers\CarController#getCars', [$param1, $param2]);
To answer your question, you should not call one controller method from another. As #elfu mentioned, this is not the intended functionality of a controller anyway. His post is correct and in your case you should probably use the User model as the location of this method, but I thought I'd at to it a little.
If you do want to share methods between multiple controllers, a good place to do this is through a Trait. In some cases, you are not referencing a model that is shared between controllers, and a Trait would be your best option.
To include a trait, you can reference it by including it at the top of your controller and then with a 'use' statement after the class declaration for the controller. Here is an example:
use App\Traits\ExampleTrait;
class CarController extends Controller
{
use ExampleTrait;
...
You would do the same in the UserController. Then, any method that you place in the ExampleTrait will be directly accessible from the CarController and the UserController by referencing it as $this->methodName(), just like referencing any other method in the same controller.
In your particular case, I would say that your logic should probably be stored in the User model, since the cars for a user are really an ATTRIBUTE of the User model, but the above gives you another option to work with.
In my humble opinion you should not call another controller in a controller.
It looks like you have some business logic in that controller. So you should move your logic to the entity (User.php) and call it in both controllers methods.
A regular controller returns a view (at least that is what is expected), so if you want to call another controller you should just send that route to that method (in web.php file) instead of calling it in another controller.
Hope that helps you.
You can call one controller function from another but the best way is to create a trait and use it both the controllers like:
trait Common
{
public function method(){}
}
class FirstController extends Controller
{
use Common;
}
class SecondController extends Controller
{
use Common;
}
If you want to bind parameters to the call, you can use:
$videos = app()->call('App\Http\Controllers\StorageController#returnViewVideo',[
'course'=>$course,
'lesson'=>$lesson,
]);
The following code worked for me well. and also it also can be used in routes.php
public function mobileImageUpload(Request $request){
$this->validate($request,[
'data'=>'required',
'filetype'=>'required',
'userid'=>'required',
]);
$namespace = 'App\Http\Controllers';
$controller = app()->make($namespace.'\ImageController');
return $controller->callAction('mobileImageUpload',[$request]);
}

Laravel, calling controller method from blade template file

Heey guys! I use Laravel 5.4, WAMP for localhost. I am struggling with the problem to call a Controller#methodName within my header.blade.php file, because I want to show in my header.blade.php file all notifications for the User. Normally I was getting all needed data with the help of routes in different pages. But for this case I need to call without using routes. Here is my code for my NotificationController:
class NotificationController extends Controller
{
public function getNotification(){
$notifications = Notification::where('user_id',Auth::user()->id)->get();
$unread=0;
foreach($notifications as $notify){
if($notify->seen==0)$unread++;
}
return ['notifications'=>$notifications, 'unread'=>$unread];
}
}
And I should receive all these data in my header file. I have used: {{App::make("NotificationController")->getNotification()}}
and {{NotificationController::getNotification() }} But it says Class NotificationController does not exist. Please heelp!
Instead of calling the controller method to get notifications, you can make a relationship method in your User model to retrieve all the notifications that belongs to the user and can use Auth::user()->notifications. For example:
// In User Model
public function notifications()
{
// Import Notification Model at the top, i.e:
// use App\Notification;
return $this->hasMany(Notification::class)
}
In your view you can now use something like this:
#foreach(auth()->user()->notifications as $notification)
// ...
#endforeach
Regarding your current problem, you need to use fully qualified namespace to make the controller instance, for example:
app(App\Http\Controllers\NotificationController::class)->getNotification()
Try using the full namespace:
For instance, App\Http\Controllers\NotificationController::getNotification
but of course, controllers aren't meant to be called the way you're using them. They're meant for routes. The better solution is to add a relationship in your user model like so:
public function notifications()
{
return $this->hasMany(Notification::class)
}
And then use this in your view like so:
#foreach(Auth::user()->notifications as $notification)

What comes in model...?

Hi I am trying to build a to do list in Laravel. It's my first time with a framework. I have actually read a lot of articles about MVC but I don't understand the meaning of model enough, and I want to learn this the correct way. So I have this code and I didn't know where to place it, in a controller or in a model?
public function getTask()
{
$tasks = DB::table('tasks')->get();
foreach ($tasks as $task) {
var_dump($task->name);
var_dump($task->description);
}
}
public function deleteTask($id)
{
DB::table('tasks')->where('id',$id)->delete();
}
public function updateTask($id)
{
DB::table('tasks')
->where('id',$id)
->update(['votes' => 1]);
}
public function createTask($name,$slug,$description)
{
DB::table('tasks')->insert(
['name' => $name],
['slug' => $slug],
['description' => $description]
);
}
I am a very new with frameworks so please be patient with my question.
the main role of models is to abstract the database layer to the framework (it is the class that talks to the database), so theoretically speaking, you would only use models to query the database (with active record class or native SQL) and return the result to the controller and the controller will do all the logic work (if...else...etc.) then send it to the view or call a model again to talk to the database ,BUT it is not uncommon in real life to see some logic code in the model althought it is considered as a bad practice in MVC world .you can read more about models for laravel here http://laravel.com/docs/5.1/eloquent
The code your showing goes in a controller.
Simply said: A model represents your table in your Database and could look as simple as this (User.php);
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//
}
The controller has the logic implementation necessary to read and modify the view through the model.
The model represents all the information that the user can control so it enables the controller access to the view and the view access to the controller, which is called as data-binding.

Laravel 5.1 - View variables(specifically current controller name) for a controller

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');
}

how to call a methode from model in a controller

I know how to call a method in model from controller but I am wondering how to call a method in controller from a model.
$this->load->model('dataOperateModel');
$this->dataOperateModel->saveData($formtype);
this loads a method in model. But I haven't seen anyone do the model to controller.
Is there any easy way to handle this.
You are not suppose to call a Controller actions from a Model. That defeats the point of data separation. I'd advise changing your question to be more specific to the problem that calling the action would solve.
To answer the question. Assuming the controller is called Posts.
//Import controller
App::import('Controller', 'Posts');
//Instantiation
$Posts = new PostsController;
//Load model, components...
$Posts->constructClasses();
//Call a method on the controller.
$Posts->index();
Please chang this:
$this->load->model('dataOperateModel','dataOperate');
$this->dataOperate->saveData($formtype);

Categories