Home > Blockchain >  how to pass user data into a json file using laravel one to one
how to pass user data into a json file using laravel one to one

Time:12-08

hello please am having issues getting user data in a json file am using one to one relationship this is my PostRequest Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PostRequest extends Model
{
    use HasFactory;

    public function user(){
        return $this->belongsTo(User::class, 'artisan_id');
    }
}

User model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
use App\Models\Verify;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;


class User extends Authenticatable
{
    use LaratrustUserTrait;
    use HasFactory, Notifiable;
    
    public function PostRequest(){
        return  $this->hasOne(PostRequest::class, 'artisan_id');
    }
}

controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

use App\Models\PostRequest;
use App\Models\User;

class ChatController extends Controller
{
    public function getMessages(){

        return view('user/message'); //response()->json($contacts);
    }
    public function getContact(){
        $email = Auth::user()->email;
        
            $contacts = PostRequest::select('artisan_id')->where('email', '=', $email)
            ->limit('1')
            ->orderBy('id', 'DESC')
            ->user();
            return response()->json($contacts);
        //}

        
    }

}

if run the above controller i get this error msg [14:09:51] LOG.error: Call to undefined method Illuminate\Database\Eloquent\Builder::user() {"userId":15,"exception":{}}

if i run this i get all data, buh den i need a specific data

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

use App\Models\PostRequest;
use App\Models\User;

class ChatController extends Controller
{
    public function getMessages(){

        return view('user/message'); //response()->json($contacts);
    }
    public function getContact(){
        $email = Auth::user()->email;
        
            $contacts = PostRequest::all();
            return response()->json($contacts);
        //}

        
    }

}

CodePudding user response:

Just try this query:

$email = Auth::user()->email;
$contacts = PostRequest::where('email', $email)->first()->user;
return response()->json($contacts);
  • Related