Ad

Laravel FindOrFail Returns All Records

- 1 answer

Not sure why this is happening. I have used the method before and everything worked just fine. For some reason findOrFail is not adding the where clause to the query to be executed. Anyone else run into this? I could just use Model::where() but I would like to figure out what's wrong if something is wrong or if I am missing something.

Route:

Route::get('/forums/topic/{id}/post/create', '[email protected]');

Controller:

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Image;
use App\PostImage;
use Auth;
use App\Topic;
use App\Post;
use App\Http\Requests\SearchRequest;
use App\Http\Requests\PostImageRequest;
use App\Http\Requests\PostRequest;
use App\Http\Requests\TopicRequest;
use App\Http\Controllers\Controller;


class ForumController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }


    /**
     * Show the form for creating a new topic.
     *
     * @return \Illuminate\Http\Response
     */
    public function topicPostCreate($id)
    {
        $results = Topic::findOrFail($id)->toSql();
        dd($results);

    }

}

Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Topic extends Model
{
    protected $fillable = [
        'title',
        'user_id'
    ];

    /**
     * Many topics belong to one user
     */
    public function user(){

        return $this->belongsTo('App\User');

    }

    /**
     * Each Topic has many posts
     * 
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

}

The query that is returned from the dd() function is as follows:

"select * from `topics`"

Anyone have any ideas as to why this is happening? There must be a good reason. Something I'm missing possibly...???

Ad

Answer

findOrFail returns a new, filled Topic-instance with a blank query. That's why you aren't seeing any where's, because the query with those in it has already been executed.

If you want to see the actual queries being run, you could try to listen to the DB queries (just put this in routes.php temporarily)

\DB::listen(function($sql) {
    dump($sql);
});
Ad
source: stackoverflow.com
Ad