Home » Php » How to call models in Laravel 5?

How to call models in Laravel 5?

Posted by: admin November 29, 2017 Leave a comment

Questions:

So, in L5 I created folder like app/Models/Blog where is file Posts.php which looks like:

<?php namespace App\Models\Blog;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model {
    protected $table = 'posts';
}

After it I executed composer dump and then in my controller:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Models\Blog\Posts as Posts;

class BlogController extends Controller {

    public function index()
    {
        $post = Posts::all()->toArray();

        dd($post);
    }
}

It throws me an error:

FatalErrorException in BlogController.php line 14: Class 'Models\Blog\Posts' not found
Answers:

Try changing this:

use Models\Blog\Posts as Posts;

To this:

use App\Models\Blog\Posts;

Questions:
Answers:

In Laravel 5.2 it’s just:

use App\Blog;

or

use App\Blog\Posts;

Questions:
Answers:

Change the following

class Posts extends Model {

to

class Posts extends \Eloquent {

Questions:
Answers:

You need to check two points :

  1. the namespace have to be in first
  2. the using must be use App\Models\Blog in your case

Like this :

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Blog;

class BlogController extends Controller {

    public function index()
    {
        $post = Posts::all()->toArray();

        dd($post);
    }
}

(tested with Laravel 5.4)

Leave a Reply

Your email address will not be published. Required fields are marked *