how to call model in laravel from controller - laravel

How to call a model in laravel.
My code is:
use Jacopo\Authentication\Models\Guide;
class SampleController extends BaseController
{
public function index()
{
$model='Guide';
$guide=$model::where('guide_link','=',"guide")->get();
print_r($guide);
}
}
This will produce Class 'Guide' not found error.

If you added your class you should run in terminal
composer dump-autoload
to update your class map. Otherwise autoloader may not "see" your class and you are getting this error.

You need to add the namespace to your string:
class SampleController extends BaseController
{
public function index()
{
$model='Jacopo\Authentication\Models\Guide';
$guide=$model::where('guide_link','=',"guide")->get();
print_r($guide);
}
}
You could also resolve it from the IoC container, but you need to register it first:
App::bind('Guide', 'Jacopo\Authentication\Models\Guide');
And then you should be able to:
$model = App::make('Guide');
$guide = $model::where('guide_link','=',"guide")->get();
But this is not a very good option

Related

Laravel 5.8 dependecy injection - how to inject model to service

I have BooksService class which should be injected by Book model object. Then I want to inject BooksService to BookController. But I dont know ho to do it.
I am getting an error Class App\Model\BookService does not exist. Is it neccesary to register it somewhere? Also I am not sure if I am doing it right. Is it in this code?
BookService
namespace App\Model;
class BookService
{
/** #var Book */
public $books;
// I am not sure if this is ok
public function construct(Book $books)
{
$this->books = $books;
}
public function test()
{
dd($this->books);
}
}
BookController
namespace App\Http\Controllers;
use App\Http\Requests\StoreBook;
use App\Model\Book;
use App\Model\BookService;
use Illuminate\Http\Request;
class BookController extends Controller
{
....
// This throws me an error BookService does not exists
public function create(BookService $bookService)
{
$bookService->test();
return view('book.create');
}
....
}
So the problem is that __contruct() method expects Book facade instance but Laravel does not know what is it. Also Book facade is available from inside the service class so no need to be injected to it.

Laravel: use extended controller or Traits or something else?

To maintain my Laravel application and save myself from a lot of duplicate code I have made the following solution:
BaseController
class BaseController extends Controller
{
public function get($id){
return $this->baseService->get($id);
}
public function getAll(){
return $this->baseService->getAll();
}
}
BaseService
class BaseService
{
protected $model;
public function __construct($model){
$this->model = $model;
}
public function get($id){
return response()->json($this->model->where('id', $id)->first());
}
public function getAll()
{
return $this->model->get();
}
}
MyController
class MyController extends BaseController
{
protected $model;
protected $baseService;
public function __construct(){
$this->model= new Model();
$this->baseService = new BaseService($this->model);
}
/**
* This controller has all the functionality from BaseController now
*/
}
What I'm wondering if this is a good method. Should I stick with this or should I use a different approach? I've heard about Traits but not sure if they are doing the same thing. It's Laravel 5.5 I'm using.
Yes, traits are used to move methods out of a controller regularly. A good example that the Laravel framework uses is the ThrottlesLogin trait. Take a look at https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Auth/ThrottlesLogins.php#L20
to see how the methods are moved outside of a controller but can be still accessed by importing the trait using the use keyword.
While traits would work for your use case I wouldn't use them here for the functionality you are looking for. I would use the repository pattern. It would better separate your code and make it more reusable.
Take a look at https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/ for more information on the repository pattern. Basically, you would separate your code into a separate repository and use Laravel's built in IoC to inject the repository into your controller.
MyController
class MyController extends Controller
{
protected $repo;
public function __construct(MyRepository $myRepository)
{
$this->repo = $myRepository;
}
public function index()
{
$myStuff = $this->repo->all();
}
// you can also inject the repository directly in the controller
// actions.
// look at https://laravel.com/docs/5.5/controllers#dependency-injection-and-controllers
public function other(MyRepository $repo)
{
$myStuff = $repo->all();
}
}
This is the perfect use case for a Trait. Traits are intended for reusable functions. They're super simple to implement, and won't take more than a few minutes to change what you have.
Here is a great article on them: https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5

Laravel abstract class auto injection

Laravel auto injects abstract class , but when there is another parameter with abstract class, Laravel ignore it and hence, getting error.
public interface PostRepository {
public function getPostById($id)
}
class EloquentPost implements PostRepository{
public function getPostById($id){
return Post::find($id);
} }
Its working fine when I use it like:
class Controller PostController {
private $post;
public function __construct(PostRepository $post)
$this->post = $post;
}
But when I use it like
class Controller PostController {
private $post;
public function __construct($someOtherParam, PostRepository $post)
$this->post = $post;
}
then Laravel show error.
Laravel is unable to determine what should be injected as the first parameter to the controller's constructor as you have no type hint for that parameter.
If that $someOtherParam is something that should come in the URL, you will be able to have that injected in controller's action method to which given route points, but not in the constructor.

how to access to laravel global Classes in packages

I am developing a Laravel package . In the packeges I need to File::delete for delete files, but The following error message is displayed :
Class 'Chee\Image\File' not found
Can you help me?
You have to declare it in the top of your class:
namespace Chee\Image;
use File;
class Whatever()
{
}
Instead of using the File Facade, you can also get it directly from the Laravel IoC container:
$app = app();
$app['files']->delete($path)
In a service provider, you can inject it as a dependency your package class:
class Provider extends ServiceProvider {
public function register()
{
$this->app['myclass'] = $this->app->share(function($app)
{
return new MyClass($app['files']);
});
}
}
And receive it in your class:
class MyClass {
private $fileSystem;
public function __construcy($fileSystem)
{
$this->fileSystem = $fileSystem;
}
public function doWhatever($file)
{
$this->fileSystem->delete($file)
}
}
You should be able to just use:
\File
Namespaces are relative to the namespace you declare for the class you are writing. Adding a "\" in front of a call to a class is saying that we want to look for this class in the root namespace which is just "\". The Laravel File class can be accessed this way because it is an alias that has an declared in the root namespace.
Assuming you have file something like that:
<?php
namespace Chee\Image;
class YourClass
{
public function method() {
File::delete('path');
}
}
you should add use directive:
<?php
namespace Chee\Image;
use Illuminate\Support\Facades\File;
class YourClass
{
public function method() {
File::delete('path');
}
}
Otherwise if you don't use PHP is looking for File class in your current namespace so it is looking for Chee\Image\File. You could look at How to use objects from other namespaces and how to import namespaces in PHP if you want

class 'base_controller' not found in Laravel 4

I have the below code in the controller.
class Authors_Controller extends Base_Controller {
public $restful = true;
public function get_index() {
return View::make('authors.index');
}
}
When i run in the browser, i am getting the error,
class 'base_controller' not found
Change
class Authors_Controller extends Base_Controller {
to
class AuthorsController extends BaseController {
Edit: you might need to leave it as "Authors_Controller" depending how your file is named - but you should change it to the Laravel 4 convention of "AuthorsController"
In addition to The Shift Exchange's answer. You might also want to rename your function to getIndex, and rename your controller to AuthorsController as Laravel 4 is camelCased.

Resources