Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, use middleware to find Domain, then get Website row using Domain row.

Tags:

php

laravel

I want to use some middleware to get a row from a website table, this row is referenced within my domains table.

This is my middleware so far:

<?php

    namespace App\Http\Middleware;

    use App\Domains;
    use Closure;

    class Domain
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {

            $domainRow = Domains::where([ 'domain' => $_SERVER['HTTP_HOST'] ])->first();

            dd($domainRow->website);

            return $next($request);
        }
    }

And here is my Domains model, which works fine except the hasOne part:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Domains extends Model
    {

        public function website()
        {
            return $this->hasOne('App\Website');
        }

    }

The hasOne part is generating the below query:

Unknown column 'websites.domains_id' in 'where clause' (SQL: select * from websites where websites.domains_id = 2 and websites.domains_id is not null limit 1)

However the query I need it to make is:

SELECT * FROM websites WHERE id = 1

Where 1 is from the website_id column within the Domains table.

like image 494
Martyn Ball Avatar asked Oct 21 '25 05:10

Martyn Ball


1 Answers

Change website method to:

public function website() 
{
    return $this->belongsTo('App\Website');
}
like image 88
wheelmaker Avatar answered Oct 23 '25 19:10

wheelmaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!