Cannot declare class App\User, because the name is already in use Laravel - laravel

I want to add user address in address table and want to update the address_id in user table for that i'm using user model and address model, data is being saved in address table but when i use User model in Address Repository
use App\Models\User;
i get
Cannot declare class App\User, because the name is already in use
Here is my code :
<?php
namespace App\Repositories;
use App\Models\Addresses;
use App\Models\User;
use App\Contracts\AddressContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
class AddressRepository extends BaseRepository implements AddressContract
{
/**
* AttributeRepository constructor.
* #param Attribute $model
*/
public function __construct(Addresses $model)
{
parent::__construct($model);
$this->model = $model;
}
public function addAddress(array $params)
{
try {
$Addresses = new Addresses($params);
$Addresses->save();
$addressId = $Addresses->id;
$userID=auth()->user()->id;
if($params['is_primary_address']==1)
{
User::where('id',$userID)->update(['address_id'=>$addressId]);
}
return $Addresses;
}
catch (QueryException $exception) {
throw new InvalidArgumentException($exception->getMessage());
}
}
}
ProductController.php
<?php
namespace App\Http\Controllers\Site;
use App\Contracts\AttributeContract;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Contracts\ProductContract;
use App\Contracts\AddressContract;
use Cart;
use Validator;
class ProductController extends Controller
{
protected $productRepository;
protected $attributeRepository;
protected $addressRepository;
public function __construct(ProductContract $productRepository, AttributeContract $attributeRepository, AddressContract $addressRepository)
{
$this->productRepository = $productRepository;
$this->attributeRepository = $attributeRepository;
$this->addressRepository = $addressRepository;
}
public function addUserAddress(Request $request)
{
$customer_name=$request->customer_name;
$customer_address=$request->customer_address;
$country=$request->country;
$city=$request->city;
$zip_code=$request->zip_code;
$state=$request->state;
$address_type=$request->address_type;
$is_primary_address=$request->primary_address;
$userID=auth()->user()->id;
$data=array('name'=>$customer_name,'address'=>$customer_address,'country'=>$country,'state'=>$state,'city'=>$city,'address_type'=>$address_type,'user_id'=>$userID,'is_primary_address'=>$is_primary_address);
$userAddress = $this->addressRepository->addAddress($data);
return redirect()->back()->with('message', 'Address Added');
}
}

Related

Laravel repository Class App\Repository\User does not exist

Hello I want to use my own repository class in my Laravel 5.8 project
I created my file Repository in the App File and in this file I added A class called ConversationRepository
This is my class:
<?php
namespace App\Repository;
class ConversationRepository{
private $user;
public function __construct(User $user){
$this->user=$user;
}
public function getConversation(int $userId){
return $this->user->newQuery()
->select('name','id')
->where('id','!=',$userId)
->get();
}
}
And then when I use it on my controller :
<?php
namespace App\Http\Controllers;
use App\User;
use Auth;
use Illuminate\Http\Request;
use App\Repository\ConversationRepository;
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository,AuthManager $auth){
$this->r = $conversationRepository;
$this->auth = $auth;
}
public function index(){
return view('conversation.index',[
'users'=>$this->r->getConversation($this->auth->user()->id)
]);
}
public function show(User $user){
return view('conversation.show',['users'=>$this->r->getConversation(
$this->auth->user()->id),
'user'=>$user
]);
}
public function store(User $user){
}
}
I get the error
Class App\Repository\User does not exist
Apparently, you forgot to add use App\User; in the class ConversationsController file.

Can't get the laravel custom repository to work

I can't get my repository working, when i'm just trying the get the entire list of documents it returns nothing
Here's my DocumentRepository
<?php
namespace App\Repositories\Document;
interface DocumentRepository
{
public function getall();
public function getById($id);
public function create(array $attributes);
public function update ($id, array $attributes);
public function delete ($id);
}
Here's the functions
<?php
namespace App\Repositories\Document;
class EloquentDocument implements DocumentRepository
{
private $model;
public function __construct(Document $model)
{
$this->model = $model;
}
public function getall()
{
return $this->model->all();
}
public function getById($id)
{
return $this->findById($id);
}
public function create(array $attributes)
{
return $this->model->create($attributes);
}
public function delete($id)
{
$this->getById($id)->delete();
return true;
}
public function update($id array $attributes)
{
$document = $this->model->findOrFail($id);
$document->update($attribute);
return $document;
}
}
and here's the controller
<?php
namespace App\Http\Controllers;
use App\Repositories\Document;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class DocumentController extends Controller
{
/**
* #var DocumentRepository
*/
private $document;
/**
* TodoController constructor.
*/
public function __construct(DocumentController $document)
{
$this->document = $document;
}
public function getalldocuments()
{
return $this->document->getAll();
}
}
For your information there's two rows of data in my Documents table/model so i just want to get both of them by just simply returning but in my case it simply returns nothing.
Here's the route
Route::get('/documents', 'DocumentController#getalldocuments');
here's the registration part insite AppServiceProviders.php
public function register()
{
$this->app->singleton(DocumentRepository::class, EloquentDocument::class);
}
You are type-hinting DocumentController instead of your actual repository.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\Document\DocumentRepository;
class DocumentController extends Controller
{
/**
* #var DocumentRepository
*/
private $document;
public function __construct(DocumentRepository $document)
{
$this->document = $document;
}
public function getalldocuments()
{
return $this->document->getAll();
}
}
Now, assuming you have properly binded the interface to resolve to your document repository implemented, this should work.
For more information on how to bind interfaces to implementation, read this: https://laravel.com/docs/5.7/container#binding-interfaces-to-implementations
Edit: You have some syntax issues in your repository's interface. You are missing function:
<?php
namespace App\Repositories\Document;
interface DocumentRepository
{
public function getall();
public function getById($id);
public function create(array $attributes);
public function update($id, array $attributes);
public function delete($id);
}
Edit 2: Your binding is correct. However, I noticed that you are not binding your App\Document model to the implementation correctly.
<?php
namespace App\Repositories\Document;
use App\Document;
class EloquentDocument implements DocumentRepository
{
private $model;
public function __construct(Document $model)
{
$this->model = $model;
}
//
//
//
}
You need to add the correct use statement at the top. Assuming your document model resides in App\Document this should work.

Override Eloquent Relation Create Method

I want to override create method, but with relation, it didn't touch the create method.
There are Two Models:
class User extends Model
{
public function user_detail()
{
return $this->hasOne(UserDetail::class);
}
}
class UserDetail extends Model
{
public static function create(array $attributes = [])
{
//I was trying to do something like
/*
if(isset($attributes['last_name']) && isset($attributes['first_name']))
{
$attributes['full_name']=$attributes['first_name'].' '.$attributes['last_name'];
}
unset($attributes['first_name'],$attributes['last_name']);
*/
Log::debug('create:',$attributes);
$model = static::query()->create($attributes);
return $model;
}
}
When I use UserDetail::create($validated), and there is a log in laravel.log, so I know the code touched my custom create method.
But if I use
$user = User::create($validated);
$user->user_detail()->create($validated);
There is no log in laravel.log, which means laravel didn't touch the create method, then how I supposed to do to override create method under this circumstance?(I'm using laravel 5.7)
Thank you #Jonas Staudenmeir, after I read the documentation, here is my solution.
If the $attributes are not in protected $fillable array, then I do it in the __construct method.
class UserDetail extends Model
{
protected $fillable=['full_name','updated_ip','created_ip'];
public function __construct(array $attributes = [])
{
if (isset($attributes['first_name']) && isset($attributes['last_name'])) {
$attributes['full_name'] = $attributes['first_name'].' '.$attributes['last_name'];
}
parent::__construct($attributes);
}
}
Otherwise, I do it in Observer.
namespace App\Observers;
use App\Models\UserDetail;
class UserDetailObserver
{
public function creating(UserDetail $userDetail)
{
$userDetail->created_ip = request()->ip();
}
public function updating(UserDetail $userDetail)
{
$userDetail->updated_ip = request()->ip();
}
}
Register Observer in AppServiceProvider.
namespace App\Providers;
use App\Models\UserDetail;
use App\Observers\UserDetailObserver;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
UserDetail::observe(UserDetailObserver::class);
}
}
I choose Observer instead of Event&Listener is for easy maintenance.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seaurchin.availableroom' doesn't exist (42S02)

I'm trying to get the available room at specified date by the client. So far I tried using join and left join to get the available room.
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\RedirectResponse;
use App\client;
use App\reservation;
use App\booking;
use App\availableRoom;
use App\roomType;
use App\amenities;
use App\payment;
use App\roomReserved;
use App\Mail\ReservationDetail;
use Carbon\Carbon;
class ReservationController extends Controller
{
private $_availablerooms;
/**
* ReservationController constructor.
*/
public function __construct()
{
$this->_availablerooms = new availableRoom();
}
/**
* #param Request $request
* #return mixed
*/
public function checkAvailable(Request $request){
$checkInDate = date("d-m-Y", strtotime($request->start_date));
$checkOutDate = date("d-m-Y", strtotime($request->end_date));
$availableRooms = $this->_availablerooms->from('availableRoom as r')
->selectRaw('*,r.roomDoorNum, r.isAvailable, rt.title as roomType,res.roomReservedID')
->join('roomtype as rt','rt.roomTypeID','=','r.roomTypeID')
->leftjoin('roomReserved as rr','rr.roomID','=','r.roomID')
->leftjoin('reservation as res','res.roomReservedID','=', DB::raw('rr.roomReservedID AND (res.reservationDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate". ' OR res.expiryDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate".')' ))
->get();
return $availableRooms;
//return view('rooms');lorem
}
}
The problem is I'm getting this error now.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'seaurchin.availableroom' doesn't exist (42S02)
availableRoom model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class availableRoom extends Model
{
protected $primaryKey = 'roomID';
protected $fillable = ['roomTypeID', 'roomDoorNum', 'isAvailable'];
public function roomAmenity()
{
return $this->hasMany('App\roomAmenity');
}
public function roomType()
{
return $this->hasOne('App\roomType');
}
public function roomAsset()
{
return $this->hasMany('App\roomAsset');
}
}
roomType model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomType extends Model
{
protected $primaryKey = 'roomTypeID';
protected $fillable = ['title', 'nightRate', 'capacity', 'childrenAllowed', 'maxAdult', 'description'];
public function availableRoom()
{
return $this->hasMany('App\availableRoom');
}
}
roomReserved model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class roomReserved extends Model
{
protected $primaryKey = 'roomReservedID';
protected $fillable = ['reservationID', 'roomID'];
public function reservation()
{
return $this->hasOne('App\Reservation');
}
}
reservation model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class reservation extends Model
{
protected $primaryKey = 'reservationID';
protected $fillable = ['reservationDate', 'expiryDate', 'paymentReceived', 'status', 'actualCheckIn', 'actualCheckOut', 'roomReservedID'];
public function booking()
{
return $this->hasOne('App\Booking');
}
public function roomReserved()
{
return $this->hasMany('App\roomReserved');
}
}

How can I add condition on mail notification laravel?

I use laravel 5.3
My notication laravel like this :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\BroadcastMessage;
class GuestRegistered extends Notification implements ShouldBroadcast, ShouldQueue
{
use Queueable;
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('test')
->greeting('Hi')
->line('Thanks')
->line('Your password : '.$this->data)
->action('Start Shopping', url('/'));
}
}
I want to add condition in toMail method
So if $this->data not exist then ->line('Your password : '.$this->data) not display or not executed
How can I do it?
Add a default value for the $data parameter in the constructor .
public function __construct($data = null)
{
$this->data = $data;
}
Then you can store the instance of MailMessage in a variable and use the if statement to add the line() you want.
public function toMail($notifiable)
{
$mailMessage = new MailMessage();
$mailMessage
->subject('test')
->greetings('Hi')
->line('Thanks');
if($this->data) {
$mailMessage->line('Your password: ' . $this->data);
}
$mailMessage->action('Start Shopping', url('/'));
return $mailMessage;
}

Resources