andremac96

Experience

5,780

0 Best Reply Awards

  • Member Since 6 Months Ago
  • 41 Lessons Completed
  • 0 Favorites

16th July, 2018

andremac96 started a new conversation Delete All Attributes In One Record Except Name And Username. • 1 month ago

Hi

I have a user table and user can delete their account and there data deletes. It's a soft delete. What I want is to delete all attributes except the name.

Can I do something like

$user->delete()->except(['name'']) ?

The record must be soft deleted just with the data removed.

11th May, 2018

andremac96 started a new conversation Acceptable Unit Test? • 3 months ago

Is this an acceptable test? I have a user model with the following fields. Name, Email, Password and UserType. I'm testing the register page. This is the testing code public function testExample() { $this->visit('/register') ->type('Andre MacNamara', 'name') ->type('[email protected]', 'email') ->type('Landlord', 'userType') ->type('password', 'password') ->press('Register') ->seePageIs('/register'); } The form has all the fields above. This is the ouput from the unit test.

Image https://i.redd.it/g4g9ehvvs8x01.png

andremac96 started a new conversation Laravel 5.6. Call To Undefined Method Visit • 3 months ago

Hi

I'm trying to test for registration using laravel.

    $this->visit('/register')
    ->type('Andre', 'name')
    ->press('Register')
    ->seePageIs('/');

I get this error

  1. Tests\Feature\UserTest::testExample Error: Call to undefined method Tests\Feature\UserTest::visit()

Any adivce

I don;t want to user dusk by the way

10th May, 2018

andremac96 left a reply on Laravel 5.6 Using Laracharts. Chart Wont Render • 3 months ago

@bashy

Yes, I have that in my aliases and in my providers i have added Khill\Lavacharts\Laravel\LavachartsServiceProvider::class,

andremac96 started a new conversation Laravel 5.6 Using Laracharts. Chart Wont Render • 3 months ago

Hi

I'm trying to test out laracharts using laravel 5.6. The chart doesn't print out in the view, only the code in text form.

Controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Khill\Lavacharts\Lavacharts;

class HomeController extends Controller
{

    public function index()
    {

        $votes  = Lava::DataTable();

        $votes->addStringColumn('Food Poll')
              ->addNumberColumn('Votes')
              ->addRow(['Tacos',  rand(1000,5000)])
              ->addRow(['Salad',  rand(1000,5000)])
              ->addRow(['Pizza',  rand(1000,5000)])
              ->addRow(['Apples', rand(1000,5000)])
              ->addRow(['Fish',   rand(1000,5000)]);
        
        Lava::BarChart('Votes', $votes);
        
        $data['votes'] = Lava::BarChart('Votes', $votes);

        
        return view('pages/home', $data);
    }
}

view

@section('content')

@barchart('Votes', 'poll_div')


@endsection

This is the output in my view. No chart only code.

enter image description here

8th May, 2018

andremac96 started a new conversation Getting Just Data Or Time From Timestamp • 3 months ago

HI

Based on the default timestamp is it possible to use either the time, or date, instead of both.

andremac96 started a new conversation Best Way To Handle Errors • 3 months ago

Hi

I asked this question on SO but got different answers. I trust this community more.

I have a controller, there gets a collection of data from a model. Whats the best way to handle the error, in the case the model is null.

public function index(){
    $messages = Message::where('sender_id', Auth::user()->id)->orWhere('recipient_id', Auth::user()->id)->get();
    return view('/pages/message/index', compact('messages'));
 }

I was told to do the following in the view before the data is called.

@if(count($messages)>0)
       //your code
@endif

@if(!empty($messages))
   //your code 

@endif

@if($messages)
   //Codes
@endif

4th May, 2018

andremac96 started a new conversation How To Run Laravel On Wamp Server • 3 months ago

Hi

How do I run Laravel on a wamp server?

Mamp broke on me this morning, so I have to install Wamp. Can I point wamp to my current directory in my dropbox folder like I can do with Mamp?

Thanks

2nd May, 2018

andremac96 started a new conversation Passing In Value Of Object Then Searching Against That Object • 3 months ago

I have a search working that finds users whose preferences match a landlords property. This is all well and good, but I want the landlord to be able to select a property, then press search, and pass that property object to be compared against.

This is an image of the search

Whichever property is chosen from the list is used to be searched against in the search.

This is the view of the search

<div class="row">
                <div class="col-md-10">
                  <select class="form-control" id="property_address" name="property_address">
                    <!--Gets all counties from DB -->
                    @foreach ($properties as $property)
                      <option value="{{$property->address . ', ' . $property->town . ', ' . $property->county}}">{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
                    @endforeach
                  </select>
                </div> <!-- ./ col-6-->
              </div> <!-- ./ row-5  -->
         
            <div class="row mt-md-4">
                <div class="col-md-4">
                    <button type="submit" class="form-control btn btn-primary">
                        Search
                    </button>
                </div>
            </div>

This is the controller

The first part renders the search form

public function searchhome(){
      //Search Filter UI
      //Populates fields.
      $user = Auth::user();
      $properties = PropertyAdvert::where('user_id', Auth::id())->get();
      return view('pages/account/search/index', compact('user', 'properties'));}

Next is the logic

public function searchresults(Request $request){
    
    //Gets all users that are tenants
    $tenants = User::where('userType', 'tenant')->first();
    
    //Gets all preferances
    $Prefereances = TenantPreferance::all()->first();
    //Gets the prefereances that match a tenant id
    $pref = $Prefereances::where('user_id', $tenants->id)->first();

    //Gets the current signed in users property

    //Attempting to get value of property by name
    $property = $request->property_address;

    $result = $pref
              ->where('county' , $property->county)
              ->where('type' , $property->type)
              ->where('rent', '<=', $property->rent)
              ->where('bedrooms', '<=', $property->bedrooms)
              ->where('bathrooms', '<=', $property->bathrooms);

    $users = $result->get();
    
    return view('pages/account/search/results', compact('users'));
  }
      

I tried using the request object to set the selected property as the one being compared against.

Any ideas?

andremac96 left a reply on Search Not Working For More Than One Parameter • 3 months ago

Perfect. Thank you.

andremac96 started a new conversation Search Not Working For More Than One Parameter • 3 months ago

I have a mini search feature. I'm trying to let a landlord find tenants whose set property preferences are equal to or great than the property.

So if the landlord has a property in Dublin with 3 beds, 2 baths.

The search will return all tenants that have specified they want a property with 3 beds or less, and 2 baths or less.

The issue I have is that only county is matching up.

These are the records that match when a tenant specifies they want a Dublin property and the landlord has a property in Dublin.

Property Record of the signed in landlord Property Record

Tenant Preferance record Property Record

This is the code

  public function searchresults(){

    //Gets all users that are tenants
    $tenants = User::where('userType', 'tenant')->first();
    
    //Gets all preferances
    $Prefereances = TenantPreferance::all()->first();
    //Gets the prefereances that match a tenant id
    $pref = $Prefereances::where('user_id', $tenants->id)->first();

    //Gets the current signed in users property
    $property = PropertyAdvert::where('user_id', Auth::user()->id)->first();

    $result = $pref::where(
      'county' , $property->county,
      'type' , $property->type,
      'rent', '<=', $property->rent,
      'bedrooms', '>=', $property->bedrooms,
      'bathrooms', '>-', $property->bathrooms
    );

    $users = $result->get();
    
    return view('pages/account/search/results', compact('users'));
  }

andremac96 left a reply on Laravel Combine Multiple Collections Into One Query • 3 months ago

@alielkhateeb The user can be either user/tenant, but only a tenant can set preferences. Only a landlord can post a property. I want a landlord to do a search, and all landlords with preferences => then the landlords active property are diplayed

1st May, 2018

andremac96 started a new conversation Laravel Combine Multiple Collections Into One Query • 3 months ago

I'm wondering if this is possible. I have 3 models. Users TenantPreferances PropertyAdverts

I'm trying to find out if I can do a query like so.

Find all tenants, whose preferences, match the currently signed in users properties.

The 3 databases are like so

User Model

 Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('userType');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

PropertyAdverts

Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->string("photo");
            $table->string('address');
            $table->string('county');
            $table->string('town');
            $table->string('type');
            $table->string('rent');
            $table->string('date');
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('furnished');
            $table->longText('description');
            $table->integer('user_id'); //Landlord ID
            $table->timestamps();
        });

Tenant Preferances

 Schema::create('tenant_preferances', function (Blueprint $table) {
        $table->increments('id');
        $table->string('county');
        $table->string('type');
        $table->string('rent');
        $table->string('bedrooms');
        $table->string('bathrooms');
        $table->boolean('status')->default('0');
        $table->integer('user_id'); //Tenant ID
        $table->timestamps();
    });

andremac96 left a reply on Different User Types Have Different Profile Page, But I Need One To Be Able To See The Others • 3 months ago

Just in regard to the relationships for landlord/tenants. How would you do that when they're both in the use model. Can you create a relationship between different objects in the same model?

andremac96 left a reply on Different User Types Have Different Profile Page, But I Need One To Be Able To See The Others • 3 months ago

That's fantastic. I just assumed all the videos were paid. Thanks

andremac96 left a reply on Different User Types Have Different Profile Page, But I Need One To Be Able To See The Others • 3 months ago

@Cronix

currenly i have users sign up a choose what their user type is (landlord, or tenant). It then goes into the user model. Should I have seperate tables for landlords, and seperate tables for tenants.

I don't have a laracasts sub atm. I'm a student, so I don't have the money atm.

andremac96 started a new conversation Different User Types Have Different Profile Page, But I Need One To Be Able To See The Others • 3 months ago

I have two user types in my application. A landlord, and a tenant. Currently when a landlord is one a tenants page, they can see the start tenant button and thats it. If a request is sent, and I try to show that, the landlord can't see the message on the tenants page, but the tenant can see it in their page/

How to I allow the landlord to see the message the tenant can see.

This is the database row (fake data)

The controller code that renders the profiles is

  public function index($id){
   //Authenticated different user types
   //Sends Landlord and Tenant to appropiate pages
   $user = User::where('id', $id)->first();
  //Allows landlords to see their relationship with tenants, and vice versa.
$landlordTenancies = Tenancy::all()->where('landlord_id', Auth::id());
$tenantTenancies = Tenancy::all()->where('tenant_id', Auth::id());

//Allows the attirbutes from the table to be access by correct landlord and tenant
$tenancy = Tenancy::where('tenant_id', Auth::id())->first();
$Tenancy = Tenancy::where('landlord_id', Auth::id())->first();

//Sends different use types to relevant view

if($user->userType == "Landlord"){
  return view('/pages/account/landlord', compact('properties', 'user', 'Watchlists', 'property', 'landlordTenancies', 'Tenancy'));
}

else{
  return view('/pages/account/tenant', compact('properties', 'user', 'Watchlists', 'property', 'tenantTenancies', 'tenancy'));
    }
  }
      }

Tenant view page

div class="container">
    <div class="row">
        <div class="col-md-12">
            @foreach($tenantTenancies as $tenancy)
            <span class="lead"><strong>Landlord Name: </strong>{{$tenancy->landlord_name}}</span><br>
            <span class="lead"><strong>Property Address: </strong>{{$tenancy->property_address}}</span><br>
            @endforeach
            
                {{-- This blocks a tenant adding themselves --}}
                {{-- Shows add button, if tenancy model is empty. Also when no relationship established. --}}
            
            @if(Auth::user()->id != $user->id)
                @if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1)
                    <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
                @elseif($tenancy->request_sent === 1)
                    <span class="text-muted">You have a tenancy request</span>
                @endif
            @endif

                {{-- Only shows following buttons, if the current signed in user, is the relevant user. --}}
                {{-- Shows accept/reject if the request has been sent, but not accepted yet. --}}

            @if(Auth::user()->id == $user->id)
                @if($tenancy != null && $tenancy->accepted == 0 && $tenancy->request_sent == 1)
                    <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
                        {{ csrf_field() }}
                        <input type="submit" class="btn btn-primary" value="Accept Request">
                    </form>

                    <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
                        {{ csrf_field() }}
                        <input type="submit" class="btn btn-warning" value="Reject Request">
                    </form>

                    {{-- Allows the tenancy to be ended. --}}
                
                @elseif($tenancy != null && $tenancy->accepted == 1 && $tenancy->request_sent == 0)
                    <form method="POST" action="/account/tenancy/{{$user->id}}/end">
                        {{ csrf_field() }}
                        <input type="submit" class="btn btn-primary" value="End Tenancy">
                    </form>
                @endif
            @endif
        </div>
    </div>

Landlord View Page

    <div class="row text-center d-flex flex-wrap">
        <div class="col-lg-12">
        @foreach($landlordTenancies as $tenancy)
            <span class="lead"><strong>Tenant Name: </strong>{{$tenancy->tenant_name}}</span><br>
            <span class="lead"><strong>Property Address: </strong>{{$tenancy->property_address}}</span><br>
        @endforeach
            <h3>Your Active Adverts</h3>
            <div class="row py-2">
            
            @foreach ($properties as $property)
                <div class="col-md-4 mb-4">
                    <a href="/property/{{$property->id}}">
                        <img class="list-image img-fluid" src="{{$property->photo}}">
                    </a>
                    <p class="mt-2">{{$property->address .', '. $property->town .', '. $property->county}}</p>
                </div>
            @endforeach
        </div> <!-- ./col -->
    </div> <!-- ./row -->
</div>  <!-- ./container -->

Currently when the landlord is on the tenant page, they can see this. Even if a request is sent, they don't see the message, request sent.

LanldlordOnTenant

When the tenant is on the tenant and they see the message request sent as well as the accept/reject buttons.

tenantOnTenantPage

I need the landlord to be able to see the request sent message, while on the tenants page, and for the tenant not to see it.

Any ideas

29th April, 2018

andremac96 left a reply on Error Method Does Not Exist, But Other Methods Are Being Found. • 3 months ago

I change $Tenancy to $Tenancy = Tenancy::all();

A dd on that results in an output of the following

https://imgur.com/a/MUv7kQh

Which is the entry in the database?

But it still isn't finding the method.

andremac96 left a reply on Error Method Does Not Exist, But Other Methods Are Being Found. • 3 months ago

Nope still the same. Would it be something to do with boolean entries in the database?

andremac96 started a new conversation Error Method Does Not Exist, But Other Methods Are Being Found. • 3 months ago

Hi

I have posted a few times, but i'm getting this weird error.

I have 3 methods in my Tenancy Model

//Helper method to clean up Tenancy/index
public function notInTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

public function hasRequestPending()
{
    return $this->accepted == 0 && $this->request_sent == 1;
}


public function inTenancy()
{
    return $this->accepted == 1 && $this->request_sent == 0;
}

hasRequestPending is not being recognized in the view, but the other two are. My error is

Method hasRequestPending does not exist. (View:

The methods are being passed in the controller via the $Tenancy variable

public function index($id){

   $user = User::where('id', $id)->first();

   $Tenancy = Tenancy::where('tenant_id', Auth::id())->get();


  return view('/pages/account/index', compact('user', 'Tenancy'));
}

In my views they're being called like so

@if(Auth::user()->id == $user->id)

You cannot add yourself

@elseif($Tenancy == null || $Tenancy->notInTenancy()) Start Tenancy @endif

      {{--  
        If the user signed in isn't the owner of this profile.
        Do not show these buttons that control accept/reject/end
      --}}

    @if(Auth::user()->id == $user->id)
      {{-- 
        If the request has been sent but hasn't been accepted.
        Give the option to accept and reject.
        This updates the values in DB.
      --}}

      @if($Tenancy->hasRequestPending())
      
      
        <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="Accept Request">
        </form>
        <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-warning" value="Reject Request">
        </form>
          <!-- 
            If the request has been accepted.
            Show button to end the tenancy,
            and property details
          -->
      @elseif($Tenancy->inTenancy())
        <form method="POST" action="/account/tenancy/{{$user->id}}/end">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="End Tenancy">
        </form>
        <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
        <h5>Your property is {{$Tenancy->property_address}}</h5>
      @endif <!-- End of current user vs this user-->
    @endif <!-- Initial If-->

The first method and third method are recognized, but number 2, is not.

andremac96 left a reply on Calling Methods In Views, That Are Defined In Models. Not Working. • 3 months ago

@bobbybouwmann

That works, but I have a question. If the db is null, I can't be accessed the "add button", so I can't populate the DB. Is there a way around this.

I have in my view

@if(Auth::user()->id == $user->id)
    <h1>You cannot add yourself</h1>
@elseif($Tenancy->addTenancy())
   <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
@endif 

The controller is calling $Tenancy like so

$Tenancy = DB::table('tenancy')->first();

This is the error i'm getting

Call to a member function addTenancy() on null

But the DB is null, so I can't access add.

andremac96 left a reply on Calling Methods In Views, That Are Defined In Controllers. Not Working. • 3 months ago

How would I give it access then?

andremac96 started a new conversation Calling Methods In Views, That Are Defined In Controllers. Not Working. • 3 months ago

Hi

I had alot of my logic in my views. I refactored this into methods in one of my models. They're being recognized, but not actually working as the IF doesn't change, as the database changes, to reflect a different method that should be called.

For example, my code was originally like this, with all the logic in the views.

@if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1) Start Tenancy @endif

          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent, but hasn't been accepted.
            Give option to accept and reject.
            This updates the values in DB.
          -->
          @if($tenancy != null && $tenancy->accepted == 0 && $tenancy->request_sent == 1)
            <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($tenancy != null && $tenancy->accepted == 1 && $tenancy->request_sent == 0)
            <form method="POST" action="/account/tenancy/{{$user->id}}/end">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with {{$tenancy->landlord_name}}</h5>
            <h5>Your property is {{$tenancy->property_address}}</h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->

I then refactored it to this, using method names instead of logc. The methods are defined in my Tenancy controller.

@if(Auth::user()->id == $tenancy->tenant_id)

You cannot add yourself

@elseif($Tenancy->addTenancy()) Start Tenancy @endif

      <!-- 
        If the user signed in, isn't the owner of this profile.
        Do not show these buttons that control accept/reject/end
      -->

    @if(Auth::user()->id == $user->id)
      <!-- 
        If the request has been sent, but hasn't been accepted.
        Give option to accept and reject.
        This updates the values in DB.
      -->
      @if($Tenancy->hasRequestPending())
        <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="Accept Request">
        </form>
        <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-warning" value="Reject Request">
        </form>
          <!-- 
            If the request has been accepted.
            Show button to end the tenancy,
            and property details
          -->
      @elseif($Tenancy->inTenancy())
        <form method="POST" action="/account/tenancy/{{$user->id}}/end">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="End Tenancy">
        </form>
        <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
        <h5>Your property is {{$Tenancy->property_address}}</h5>
      @endif <!-- End of current user vs this user-->
    @endif <!-- Initial If-->

This is the controller which renders the view above

  public function index($id){

   $user = User::where('id', $id)->first();
   $users = Auth::user();
   $Tenancy = new Tenancy;
   $tenancy =  DB::table('tenancy')->first();

  return view('/pages/account/index', compact('user', 'users', 'Tenancy', 'tenancy'));
}

This is the Tenancy model where the methods are defined.

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

public function hasRequestPending()
{
    return $this->accepted == 0 && $this->request_sent == 1;
}

public function inTenancy()
{
    return $this->accepted == 1 && $this->request_sent == 0;
}

I can't see why the newly update view shouldn't be moving through the IF statement as the database changes. Any ideas?

28th April, 2018

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

@ohffs

Is there something else I need to do. The if statement isn't moving down the cases

This is what i'm declaring in the controller $tenancy = new Tenancy; $Tenancy = DB::table('tenancy')->first()

@if(Auth::user()->id == $tenancy->tenant_id)

You cannot add yourself

@elseif($Tenancy->addTenancy()) Start Tenancy @endif

      <!-- 
        If the user signed in, isn't the owner of this profile.
        Do not show these buttons that control accept/reject/end
      -->

    @if(Auth::user()->id == $user->id)
      <!-- 
        If the request has been sent, but hasn't been accepted.
        Give option to accept and reject.
        This updates the values in DB.
      -->
      @if($Tenancy->hasRequestPending())
        <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="Accept Request">
        </form>
        <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-warning" value="Reject Request">
        </form>
          <!-- 
            If the request has been accepted.
            Show button to end the tenancy,
            and property details
          -->
      @elseif($Tenancy->inTenancy())
        <form method="POST" action="/account/tenancy/{{$user->id}}/end">
          {{ csrf_field() }}
          <input type="submit" class="btn btn-primary" value="End Tenancy">
        </form>
        <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
        <h5>Your property is {{$Tenancy->property_address}}</h5>
      @endif <!-- End of current user vs this user-->
    @endif <!-- Initial If-->

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

@ohffs

I have one more issue.

I have called an instance of the array like you suggested, but I cant access data. Printing out the $Tenancy variable returns an empty array.

<h1>Tenant ID {{ $Tenancy->tenant_name }}</h1>

Doesn't return the tenant name. Just the preceding text.

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

I found the solution. It was actually very simple, and obvious.

I wasn't calling an function, i was calling a relationshop. Duh?

I needed to call

@if($Tenancy->addTenancy()) 

using the '()', to call a function, rather than calling

@if($Tenancy->addTenancy)

without the '()', as a relationship.

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

@ohffs

I'm getting an error when calling the method.

App\User::addTenancy must return a relationship instance. (View: /index.blade.php)

This was my original line in index.blade.php

@if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)

I changed it to this

@elseif($Tenancy->addTenancy)

And moved the logic to my Tenancy model like so

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

Perfect. Thanks alot @ ohffs. It looks so much cleaner

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

@Cronix Some good points. I'll split up the views. I regard to the forms, each one holds a button it's posted to a different controller, via a different route. Is this not the correct way to do it?

andremac96 left a reply on Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

@ohffs

You have made some very valid points that I have overlooked. Thank you for your help. Just one question, where would I write the method hasPendingRequest? Is it better off in the controller, or the model?

And would I use the same logic eg

public function hasPendingRequest(){ if($Tenancy != null && $Tenancy->accepted == 0 && $Tenancy->request_sent == 1){ render the button..... } }

andremac96 started a new conversation Can Some Review My Code And See How I'm Doing - Users Adding Eachother In Laravel • 3 months ago

Hi

I'm looking for a code review for the following system that I created.

Any advice will be appreciated. I'm only a few months into Laravel, so i'm not sure if im doing this right, or wrong.

It allows a landlord, to add a tenant to start a tenancy. It has added, accept, reject, and prohibits a tenant from adding themselves. Tenants can't add landlords.

First thing up is my controller

The form is what is rendered when the landlord clicks add. It prepopulates with landlord name and id. The tenant's name, and id, and also the landlord's properties.

Create a Tenancy

These are the columns in the db

/Renders Form
  public function create($id){
    $user = User::where('id', $id)->first();
    $properties = PropertyAdvert::where('user_id', Auth::id())->get();

    return view('/pages/account/tenancy/create', compact('user', 'properties'));
  }

  //Stores data
  public function store(Request $request, User $user){
    $properties = PropertyAdvert::where('user_id', Auth::id())->get();
    $Tenancy = Tenancy::create([
      'tenant_id' => $request->tenant_id,
      'tenant_name' => $request->tenant_name,
      'landlord_id' => $request->landlord_id,
      'landlord_name' => $request->landlord_name,
      'property_address' => $request->property_address,
    ]);

    //Redirct somewhere
  }
  
  public function accept(Request $request){
    Tenancy::where('accepted', 0)->where('request_sent', 1)
            ->update(
              [
                'accepted' => 1,
                'request_sent' => 0,
              ]
              
            );
    return back();
  }

  public function reject(Request $request){
    Tenancy::where('accepted', 0)->where('request_sent', 1)
            ->update(
              [
                'accepted' => 0,
                'request_sent' => 0,
              ]
            );
    return back();
  }
  
  public function end(Request $request){
    Tenancy::where('accepted', 1)->update(
      [
        'accepted' => 0,
      ]
    );
    return back();
  }

This is the view This is the tenants page. Only the landlord can add, but only the tenant can accept/reject and end the tenancy. Different buttons appear based on the bolleans in the db

  <div class="container">

  <!-- ============== Tenant Profile section ============== -->
  
    @if($user->userType != "Landlord")
      <div class="row">
        <!-- 
          If the request hasn't been sent, and hasn't been excepted.
          Provie button to send a tenancy request
        -->

        <!-- 
          If tennancy = null
          if tennacny not accepted
          if request hasn't been sent
          if currently signed in user != user/tenant id
        -->
        @if(Auth::user()->id == $user->id)
          <h1>You cannot add yourself</h1>
        @elseif($Tenancy == null || $Tenancy->accepted == 0 && $Tenancy->request_sent != 1)
          <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
        @endif

          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent, but hasn't been accepted.
            Give option to accept and reject.
            This updates the values in DB.
          -->
          @if($Tenancy != null && $Tenancy->accepted == 0 && $Tenancy->request_sent == 1)
            <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($Tenancy != null && $Tenancy->accepted == 1 && $Tenancy->request_sent == 0)
            <form method="POST" action="/account/tenancy/{{$user->id}}/end">
              {{ csrf_field() }}
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
            <h5>Your property is {{$Tenancy->property_address}}</h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->
      </div>

      <div class="row mt-4">
        <div class="col-md-9">
          <span class="text-lead text-center">Your watched properties</span>
          <hr>
          <div class="row py-2">
            @foreach ($user->WatchedProperties as $WatchedProperties)
              <div class="col-md-4 mb-4">
                <a href="/property/{{$WatchedProperties->image_info}}">
                  <img class="list-image img-fluid" src="{{$WatchedProperties->image_url}}">
                </a>
                <p class="mt-2">{{$WatchedProperties->address .', '. $WatchedProperties->town .', '. $WatchedProperties->county}}</p>
              </div>
            @endforeach
          </div>
        </div>
        <div class="col-md-3 spacing">
          <table class="table">
            <tbody>
              <!--
                Looping thorugh all watchlists.
                Watchlist controller Index
              -->
              <a href="#" class="link-sub-title">Property Preferences</a>
              <p class="text-sub-title">Your Watchlists</p>
              @foreach ($Watchlists as $Watchlist)
                <tr>
                  <td>
                    <a href="/watchlist/{{$Watchlist->id}}">
                      {{$Watchlist->title}}
                    </a>
                  </td>
                </tr>
              @endforeach
            </tbody>
          </table>
        </div>
      </div>

andremac96 started a new conversation Transferring Logic From Views, To Controller • 3 months ago

I have written all my logic for a feature in my app into the view. What would be the best/most efficient way of removing most of the logic into a controller?

Here is the view

This control what buttons are showns based on what a user has cliked on

<div class="container">
  @if($user->userType != "Landlord")
    <div class="row">
      <!-- 
        If the request hasn't been sent, and hasn't been excepted.
        Provie button to send a tenancy request
      -->
      @if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)
        <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->
          @if(Auth::user() != $user->id)
            <!-- 
              If the request has been sent, but hasn't been accepted.
              Give option to accept and reject.
              This updates the values in DB.
            -->
            @elseif($Tenancy->accepted == 0 && $Tenancy->request_sent == 1)
              <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
                {{ csrf_field() }}
                <button class="btn btn-primary" value="Accept Request"></button>
              </form>
              <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
                {{ csrf_field() }}
                <button class="btn btn-warning" value="Reject Request"></button>
              </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
            @elseif($Tenancy->accepted == 1 && $Tenancy->request_sent == 0)
              <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
                {{ csrf_field() }}
                <button class="btn btn-primary" value="End Tenancy"></button>
              </form>
                <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
                <h5>Your property is {{$Tenancy->property_address}}</h5>
          @endif <!-- End of current user vs this user-->
      @endif <!-- Initial If-->

This is the controller The functions here render the form, show the data, and update the boolean value in DB if a request is accepted, or rejected (not complete 100%)

  //Renders Form
  public function create($id){
    $user = User::where('id', $id)->first();
    $properties = PropertyAdvert::where('user_id', Auth::id())->get();

    return view('/pages/account/tenancy/create', compact('user', 'properties'));
  }

  //Stores data
  public function store(Request $request, User $user){
    $properties = PropertyAdvert::where('user_id', Auth::id())->get();
    $Tenancy = Tenancy::create([
      'tenant_id' => $request->tenant_id,
      'tenant_name' => $request->tenant_name,
      'landlord_id' => $request->landlord_id,
      'landlord_name' => $request->landlord_name,
      'property_address' => $request->property_address,
    ]);

    //Redirct somewhere
  }
  
  public function accept(Request $request){
    Tenancy::where('accepted', 0)->where('request_sent', 1)
            ->update(
              [
                'accepted' => 1,
                'request_sent' => 0,
              ]
              
            );
    return back();
  }

 public function reject(Request $request){

}

27th April, 2018

andremac96 started a new conversation Created A Friend Request System, 'object Not Found Error; If There Isn't Already Data In The Database • 3 months ago

I created a "Friend System" for Landlord to add a tenant to start a tenancy and allow the tenant accept the request. It works almost perfectly.

If there is no data in the database, the landlord can't view the tenant profile to add them, as there are no objects in the database.

The error is

Trying to get property of non-object

This points to the second if statement, and works it's way down as you delete the section of the if statement.

How do I show the start tenancy button, if the objects are null

This is the code

  @if($user->userType != "Landlord")
    <div class="row">
      <!-- 
        If the request hasn't been sent, and hasn't been excepted.
        Provie button to send a tenancy request
      -->
      @if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)
        <a href="/account/tenancy/{{$user->id}}/create" class="btn btn-primary">Start Tenancy</a>
          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->
          @if(Auth::user() != $user->id)
            <!-- 
              If the request has been sent, but hasn't been accepted.
              Give option to accept and reject.
              This updates the values in DB.
            -->
            @elseif($Tenancy->accepted == 0 && $Tenancy->request_sent == 1)
              <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
                {{ csrf_field() }}
                <button class="btn btn-primary" value="Accept Request"></button>
              </form>
              <form method="POST" action="/account/tenancy/{{$user->id}}/reject">
                {{ csrf_field() }}
                <button class="btn btn-warning" value="Reject Request"></button>
              </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
            @elseif($Tenancy->accepted == 1 && $Tenancy->request_sent == 0)
              <form method="POST" action="/account/tenancy/{{$user->id}}/accept">
                {{ csrf_field() }}
                <button class="btn btn-primary" value="End Tenancy"></button>
              </form>
                <h5>Currently in Tenancy with {{$Tenancy->landlord_name}}</h5>
                <h5>Your property is {{$Tenancy->property_address}}</h5>
          @endif <!-- End of current user vs this user-->
      @endif <!-- Initial If-->
    </div>

andremac96 left a reply on Best Way To Turn This Add Tenant Method Into A Request That Can Be Accepted/rejected • 3 months ago

@martinbean. That is exactly what i'm after. A tenant can accept the request or reject it.

The data is only mock data I entered into the system. This isn't a commercial project, more of a learning project.

andremac96 started a new conversation Best Way To Turn This Add Tenant Method Into A Request That Can Be Accepted/rejected • 3 months ago

Hi I'm building a sample app in Laravel based around tenancies. Landlords can add tenants, but it's not a accept/request system. Once the Landlord clicks add, and fills out a form, the tenancy is create. This is a sample row in the database.

Database row. I added the accepted method so a tenant can accept/reject, but it's just sitting there atm, it's not doing anything (yet). How can I allow the 'add' to be a request, and for the landlord to accept or reject it. This is the profile page. I was thinking of having the logic like this. How hard is it?

@if($user->userType != "Landlord") `//Add Tenancy - I'll start this so only lanlors can see this button` `Start Tenancy`
    `//If Tenancy request sent`
    `button to accept or reject.`

`//If if in tenacny`
    `list property address, or landlord name`
</div>

26th April, 2018

andremac96 started a new conversation Error While Trying To Send 'friend' Request To Connect To Users - Laravel • 3 months ago

I'm creating an application using Laravel and Eloquent. I'm trying to allow a user add another user, and associate the relationship between them, with a property which belongs to a landlord.

This is my create a form, where the property is chosen and is prefilled with the names and landlord properties.

<form action="/account/{{$user->id}}/add" method="POST">
              {{ csrf_field() }}
                  <select class="form-control" id="property_address" name="property_address">
                    <!--Gets all counties from DB -->
                    @foreach ($properties as $property)
                      <option value={{$property->id}}>{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
                    @endforeach
                  </select>

                  <label for="landlord-name">Landlord Name</label>
                  <select class="form-control" name="landlord-name">
                    <option value="{{Auth::user()->name}}">{{Auth::user()->name}}</option>
                  </select>

                  <label for="tenand-name">Tenant Name</label>
                  <select class="form-control" name="tenant-name">
                    <option value="{{$user->name}}">{{$user->name}}</option>
                  </select>
              <button class="mt-2 btn btn-primary" type="submit">Create Tenancy</button>
            </form> <!-- ./form -->

That produces this form. The details are populated based on the landlord who clicked the tenant/ or vice versea.

This is the form image

The users click add, and I want to get the details into the database called 'tenancies' like so.

I need to get the property address, or an id in the property_address field.

enter image description here

These are the errors being thrown.

55 Illuminate\Database\Eloquent\Relations\BelongsToMany attach …\app\User.php

The line is

   //Add tenancy
    public function addTenancy(User $user){
      $this->tenancyOf()->attach($user->id)->attach($property->id);
    }

then this one

86App\User addTenancy …\app\Http\Controllers\AccountController.php58

The line is in the bolded line in the method get add

public function getAdd($id){ $user = User::where('id', $id)->first();

//Check if tenancy already exists
if(Auth::user()->isInTenancyWith($user)){
  return redirect('/account/{{$user->id}}')->with('status', "Already i a tenancy");
}

//After passing all checks. Add other account
//Landord is adding the tenant
**Auth::user()->addTenancy($user);**

return redirect('/account/{{$user->id}}')->with('status', "Request Sent");

}

Any advice here. I had it working fine, before I added the address in. But I don't know why the property isn't going in.

I can link to github repo, if this explanation isn't good enough.

Entire error added: Edit

enter image description here

Edit: TenancyOf Relationship

public function tenancyOf(){
      return $this->belongsToMany('App\User', 'tenancies', 'tenancy_id', 'user_id', 'property_address');
    }

enter image description here

21st April, 2018

andremac96 started a new conversation How Do I Go About Testing In Laravel • 4 months ago

I started learning Laravel earlier this year, and I want to get into testing. I have never written a test in any language, and I have no idea how to start.

For example. I have a function below, that performs the logic of a search filter. How would I perform a test, what's the point of testing, if I have validation?

    public function search(Request $request){
      //Search Filter Logic

      //Validation

      $this->validate($request, [
        "county" => "required",
        "town" => "required",
        "type" => "required",
        "min-bedrooms" => "required",
        "max-bedrooms" => "required",
        "min-bathrooms" => "required",
        "max-bathrooms" => "required",
        "min-rent" => "required|max:4",
        "max-rent" => "required|max:4",
      ]);

      $user = Auth::user();
      $query = PropertyAdvert::query();
      $options = [];

      //Fills options array with county, town and yupe
      if ($request->has('county')) {
          $options['county'] = $request->input('county');
      }

      if ($request->has('town')) {
          $options['town'] = $request->input('town');
      }

      if($request->has('type')){
        $options['type'] = $request->input('type');
      }

      //Preforms query on options array
      if ($options) {
          $query->where($options);
      }

      //Bedrooms
      /*
      *  Checks Min
      *  Checks Max
      *  Results in min -> Max and in between being returned
      *  For Bed, Bath and Rent
      */

      if ($request->has('min-bedrooms')) {
          if ($request->has('max-bedrooms')) {
              $query->whereBetween('bedrooms', [
                  $request->input('min-bedrooms'),
                  $request->input('max-bedrooms')
              ]);
          } else {
              $query->where('bedrooms', '>', $request->input('min-bedrooms'));
          }
      } elseif ($request->has('max-bedrooms')) {
          $query->where('bedrooms', '<', $request->input('max-bedrooms'));
      }

      //Bathrooms
      if ($request->has('min-bathrooms')) {
          if ($request->has('max-bathrooms')) {
              $query->whereBetween('bathrooms', [
                  $request->input('min-bathrooms'),
                  $request->input('max-bathrooms')
              ]);
          } else {
              $query->where('bathrooms', '>', $request->input('min-bathrooms'));
          }
      } elseif ($request->has('max-bathrooms')) {
          $query->where('bathrooms', '<', $request->input('max-bathrooms'));
      }

      //Rent
      if ($request->has('min-rent')) {
          if ($request->has('max-rent')) {
              $query->whereBetween('rent', [
                  $request->input('min-rent'),
                  $request->input('max-rent')
              ]);
          } else {
              $query->where('rent', '>', $request->input('min-rent'));
          }
      } elseif ($request->has('max-rent')) {
          $query->where('rent', '<', $request->input('max-rent'));
      }

      $properties = $query->get(); //Gets all
}

25th March, 2018

andremac96 started a new conversation Creating A "tenancy Between Two Users" • 4 months ago

I'm creating a property app and I need to let users start a "tenancy with eachother". I have two types of users in one database. One as a landlord, and one as a tenant. I want the landlord to go to the tenants profile, click create, open a form and then the landlord picks one of his assoicated properties. The tenant can can accept/reject this.

I took a friend system, and changed it to tennacy and of course that worked. But when I tried to add a property to the table I ran into all sorts of issue. I don't think it's written well as I didn't even get responses here.

So whats the best way to go about this. I have user profiles, landlords can upload properties ect. But I need a specific property assoicated with the tenancny.

Here is a scalled down property table.

Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->string("photo");
            $table->string('address');
});

Here is the tenancy table

Schema::create('tenancies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('tenancy_id');

  //Works find without the below column. I need to associate a property with a tenancy.
            $table->string('property_address');
            $table->boolean('accepted')->default('0');
        });

andremac96 started a new conversation How Would I Go About Adding A Property Address Value To A Column In My Tenancy Table (friends Table) • 4 months ago

Ok.

I'm building a prroperty app. I have a friends system implemeneted in the app. I'm using this to allow a landlord to add a tenant and this works as a connection. My question is how would I assoicated one of the landlords poperties with the request when it is send.

At the moment, when a request is sent, the following is posted to the database. User_id (Landlord), Tenancy_id (Tenant), Accepted (false). I would like to post a property address with this also, but I'm stuck on how to do that.

I have a form, where I have the landlords name, and tenants name, but also a list of the landlords property. I have no idea how to send this to the database. As it's not a normal store method. I will post the code.

The add method in the ACCOUNT CONTROLLER

  public function getAdd($id){
    $user = User::where('id', $id)->first();

    //If the user can be found
    if(!$user){
      return redirect('/')->with(['status', 'Profile Not Found']);
    }

    if(Auth::user()->id === $user->id){
        return redirect()->route('home');
    }

    //If current sign in user has request pending with the users
    //If the uer has a request pending with auth user
    if (Auth::user()->hasTenancyRequestsPending($user) ||
        $user->hasTenancyRequestsPending(Auth::user())){
          return redirect('/account/{{$user->id}}')->with('status', "Friend request already pending");
      }

    //Check if tenancy already exists
    if(Auth::user()->isInTenancyWith($user)){
      return redirect('/account/{{$user->id}}')->with('status', "Already i a tenancy");
    }

    //After passing all checks. Add other account
    //Landord is adding the tenant
    Auth::user()->addTenancy($user);

    return redirect('/account/{{$user->id}}')->with('status', "Request Sent");
  }

The create FORM The properties variable is loaded from a controller which holds all properties owned by a landlord.

<form action="/account/{{$user->id}}/add" method="POST">
              {{ csrf_field() }}
                  <select class="form-control" id="property_address" name="property_address">
                    <!--Gets all counties from DB -->
                    @foreach ($properties as $property)
                      <option value={{$property->id}}>{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
                    @endforeach
                  </select>
              
                  <label for="landlord-name">Landlord Name</label>
               
                  <select class="form-control" name="landlord-name">
                    <option value="{{Auth::user()->name}}">{{Auth::user()->name}}</option>
                  </select>
              
                  <label for="tenand-name">Tenant Name</label>
               
                  <select class="form-control" name="tenant-name">
                    <option value="{{$user->name}}">{{$user->name}}</option>
                  </select>
                
              <button class="mt-2 btn btn-primary" type="submit">Create Tenancy</button>
            </form> <!-- ./form -->

THE User model which has the methods to add friends

//Tennancies of this uers. User model, tenancy table.
public function tenanciesOfMine(){
  return $this->belongsToMany('App\User', 'tenancies', 'user_id', 'tenancy_id');
}

//Users who have this user as a friend
//Inverse of user tenncies -> Both users have tenancy if one exists. One user can't be in a tenancy with someone who is not in tenacy with them.
//Like friends on FB. You can't be friends with someone, without them being friends with you also.
public function tenancyOf(){
  return $this->belongsToMany('App\User', 'tenancies', 'tenancy_id', 'user_id');
}

//If a tenancy is accepted, create the tenancy ie friendship.
public function tenancies(){
  //Getting friends of this user. Where accepted is true
  return $this->tenanciesOfMine()->wherePivot('accepted', true)->get()->
  //merge the inverse. Tennancy created with both users
    merge($this->tenancyOf()->wherePivot('accepted', true)->get());
}

//Request hasn't yet been accepted. Display list  of pending requests
public function tenacyRequests(){
  return $this->tenanciesOfMine()->wherePivot('accepted', false)->get();
}

//Inverse of Tenancy Requests
public function tenancyRequestsPending(){
  return $this->tenancyOf()->where('accepted', false)->get();
}

//If a user has a request pending from another user
public function hasTenancyRequestsPending(User $user){
  return (bool) $this->tenancyRequestsPending()->where('id', $user->id)->count();
}

public function hasTenancyRequestsReceived(User $user){
  return (bool) $this->tenacyRequests()->where('id', $user->id)->count();
}

//Add tenancy
public function addTenancy(User $user){
  $this->tenancyOf()->attach($user->id);
}

//Add tenancy
public function acceptTenancyRequest(User $user){
  $this->tenacyRequests()->where('id', $user->id)->first()->pivot->update([
    'accepted' => true,
  ]);
}

Here are the migrations for Tenancies (Which holds the landlord and Tenant) relationship.

  Schema::create('tenancies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('tenancy_id');
            $table->string('property_address');
            $table->boolean('accepted')->default('0');
        });

And for property

Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->string("photo");
            $table->string('address');
});

17th March, 2018

andremac96 started a new conversation Laravel: Array To String Conversion. Posting Form • 5 months ago

I'm trying to post a form to a database but I'm getting an error when submitting

Array to string conversion. I'm trying to upload multiple photos, as such this is an array of multiple items.

Any suggestions on how fix this.

This is mycontroller

public function store(UploadRequest $request){

      $Advert = PropertyAdvert::create($request->all());
      foreach ($request->photos as $photo) {
          $filename = $photo->store('photo');
          PropertyAdvert::create([
              'property_id' => $property->id,
              'filename'    => $filename,
              "address"     => $address,
              "county"      => $county,
              "town"        => $town,
              "type"        => $type,
              "rent"        => $rent,
              "date"        => $date,
              "bedrooms"    => $bedrooms,
              "bathrooms"   => $bathrooms,
              "furnished"   => $furnished,
              "description" => $description,
              "user_id" => Auth::id(),
          ]);
      }

    $id = $Advert->id;

    return redirect("/property/$id");
  }

Photo form field

  <form method="POST" action="/property" enctype="multipart/form-data">
                        {{ csrf_field() }}
                        
                          <div class="form-group row">
                              <label for="photo" class="col-md-3 col-form-label text-md-right">Images</label>
                              <div class="col-md-9">
                                <input required type="file" class="form-control" name="photo[]" multiple>
                              </div>
                            </div>

Upload request field

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UploadRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
          return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
      $rules = [
        "photo" => "required|array",
      ];
      $photos = count($this->input('photos'));
      foreach(range(0, $photos) as $index) {
          $rules['photos.' . $index] = 'image|mimes:jpeg,bmp,png|max:2000';
      }

      return $rules;
    }
}

11th March, 2018

andremac96 left a reply on Ttemping To Upload Multiple Photos Instead Of 1. Appears To Upload, But I Cant Display Them. • 5 months ago

@bobbybouwmann Would you happen to know of any good tutorials for this?

andremac96 started a new conversation Ttemping To Upload Multiple Photos Instead Of 1. Appears To Upload, But I Cant Display Them. • 5 months ago

I have a property ad, which has a field to upload photos. It 'seems' to upload them with no errors, but I can't display them. I get the missing image icon. Here is my code

FORM

          <form method="POST" action="/property" enctype="multipart/form-data">
                {{ csrf_field() }}
                  <div class="form-group row">
                      <label for="photo" class="col-md-3 col-form-label text-md-right">Images</label>
                      <div class="col-md-9">
                        <input required type="file" class="form-control" name="photo[]" placeholder="address" multiple>
                      </div>
                    </div>

         </form>

Store Controller

public function store(Request $request){

      $input=$request->all();
      $images=array();
      if($files=$request->file('photo')){
        foreach($files as $file){
          $name=$file->getClientOriginalName();
          $file->move('photo', $name);
          $images[]=$name;
        }
      }
    $Advert = PropertyAdvert::create([
        //"photo"       => base64_encode(file_get_contents($request->photo->path())),
        'photo'=>  implode("|",$images),
        "address"     => $request->address,
        "county"      => $request->county,
        "town"        => $request->town,
        "type"        => $request->type,
        "rent"        => $request->rent,
        "date"        => $request->date,
        "bedrooms"    => $request->bedrooms,
        "bathrooms"   => $request->bathrooms,
        "furnished"   => $request->furnished,
        "description" => $request->description,
        "user_id" => Auth::id(),
    ]);

    $id = $Advert->id;

    return redirect("/property/$id");
  }

Any ideas?

EDIT

This is the migration file. As you can see the photo field is the first one.

Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->binary('photo');
            $table->string('address');
            $table->string('county');
            $table->string('town');
            $table->string('type');
            $table->string('rent');
            $table->string('date');
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('furnished');
            $table->longText('description');
            $table->integer('user_id');
            $table->timestamps();
        

Show Page Code

<div class="card-body col-md-12">
      @foreach ($Advert as $Ad)
        <img src="data:image/gif;base64,{{ $Ad['photo'] }}" class="img-fluid full-width col-md-12">
      @endforeach
  
    </div>

23rd February, 2018

andremac96 left a reply on How Do I Upload Multiple Photos In Laravel. • 5 months ago

I have tried that previously and unfortunately ran into errors that I could not be solved. The same solution was everywhere and did not resolve the issue.

andremac96 started a new conversation How Do I Upload Multiple Photos In Laravel. • 5 months ago

I'm creating an add where users need to submit data though a form. I would them to be able to upload multiple photos through the form, and have the photos related to the data in the form.

Any good tutorials for this?

andremac96 left a reply on Laravel - Posting Image To Database - Issue Retrieving It • 5 months ago

By "create a separate model (Photo with a field 'src')" does that mean i need that in my migration

21st February, 2018

andremac96 left a reply on Laravel - Posting Image To Database - Issue Retrieving It • 6 months ago

This only seems to upload one photo. I have also included the multipart in my form

andremac96 left a reply on Laravel - Posting Image To Database - Issue Retrieving It • 6 months ago

Do I need to make changes to my migraiton file then lostdreamer?

andremac96 started a new conversation Laravel - Posting Image To Database - Issue Retrieving It • 6 months ago

I'm trying to allow a user to post an image to a database along with various other bits of information. It posts perfect. I'll show the code to how I post it.

When I try to display it, as shown in the template below, it returns the missing image icon, or if I have it as an h1, a path, but that path does not exist.

Is there something I'm doing wrong in the way i'm sending it the database that doesn't format it correctly. Controller

public function store(Request $request){
      $Advert = new PropertyAdvert();

      $Advert::create(
        [
          "photo"       => $request->photo,
          "address"     => $request->address,
          "county"      => $request->county,
          "town"        => $request->town,
          "type"        => $request->type,
          "rent"        => $request->rent,
          "date"        => $request->date,
          "bedrooms"    => $request->bedrooms,
          "bathrooms"   => $request->bathrooms,
          "furnished"   => $request->furnished,
          "description" => $request->description
        ]
      );

      return "Success. Your adveret has been published";
    }

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PropertyAdvert extends Model
{
     protected $fillable = ["photo", "address", "county", "town","type","rent","date","bedrooms","bathrooms","furnished","description",];
}

Migration

  public function up()
    {
        Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->binary('photo');
            $table->string('address');
            $table->string('county');
            $table->string('town');
            $table->string('type');
            $table->string('rent');
            $table->string('date');
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('furnished');
            $table->longText('description');
            $table->timestamps();
        });
    }

Template

<div>
    <div class="row">
      <div class="col-md-10">
        <h1>{{$Advert->id}}</h1>

        <img src="{{$Advert->photo}}">
        <h1>{{$Advert->address}}</h1>
        <h1>{{$Advert->county}}</h1>
        <h1>{{$Advert->town}}</h1>
        <h1>{{$Advert->type}}</h1>
        <h1>{{$Advert->rent}}</h1>
        <h1>{{$Advert->date}}</h1>
        <h1>{{$Advert->bedrooms}}</h1>
        <h1>{{$Advert->bathrooms}}</h1>
        <h1>{{$Advert->description}}</h1>
      </div>

    </div>


@endsection

19th February, 2018

andremac96 left a reply on Unable To Guess The Mime Type As No Guessers Are Available (Did You Enable The Php_fileinfo Extension?) • 6 months ago

Yes It's enabled.

In the configure command section it shows "--enable-fileinfo" which is what I enabled in php.ini

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.