Jose Cerejo
Jose Cerejo

Reputation: 231

eloquent relationships and hasmany laravel 5

I'm working on laravel and I am exceedingly difficult to realize this error. "Call to a member function first () on null" The error is a bit weird as if the user has a record in the database table the code works right but if it is a new record and you do not have any record in the database in redessocias table asks me this error "Call to a member function first () on null" Any idea for this problem?

Class User

public function redessociais(){ 
    return $this->hasMany('App\RedesSociais','id_user','id')->first(); 
}

Class RedesSociais

public function user()  {
    return $this->belongsTo('App\User');
}   

Controller

    public function updateSocial() { 
        $redesociais = Input::except('_token'); 
        $redesociais['id_user'] = Auth::user()->id; 
        $validation = Validator::make($redesociais, RedesSociais::$redesociais); 
        if ($validation->passes()) {
            if($user = RedesSociais::find(Input::get('id'))->first()) {
                $user -> update($redesociais); 
            }else{ 
                $user = RedesSociais::insert($redesociais); 
            } 
        Session::flash('redes_sociais', 'Redes sociais editadas com sucesso'); 
        return Redirect::to('backend/perfil/redes_sociais'); 
        } else { 
        return Redirect::to('backend/perfil/redes_sociais')->withInput()->withErrors($validation); 
        } 
    }

Social.blade.php

    {!! Form::open(array('class' => 'form-horizontal', 'url' => 'backend/perfil/redes_sociais', 'name' => 'updateSocial', 'role' => 'form'))!!}

    <input type="hidden" name="id" value="{{Auth::user()->id}}">

    <div class="row">
        <div class="col-md-3 col-lg-3"></div>
        <div class="col-md-7 col-lg-7">
            @if (count($errors) > 0)
                <div class="alert alert-danger" style="margin-top: 0px;">
                    <strong>Ups!</strong> Existe algum problema com o formulário.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
        </div>
    </div>
    <div class="row">
        <div class="col-md-3 col-lg-3"></div>
        <div class="col-md-7 col-lg-7">
            @if (Session::has('redes_sociais'))
                <div class="alert alert-success" style="margin-top: 0px;">
                    {{ Session::get('redes_sociais') }}
                </div>
            @endif
        </div>
    </div>        
    <div class="row" style="margin-bottom: 20px;">
        <div class="col-md-3 col-lg-3"></div>
        <div class="col-md-2 col-lg-2">
            {!! Form::label('facebook', 'Facebook', ['class' => 'label_perfil']) !!}
        </div>
        <div class="col-md-5 col-lg-5">
                {!! Form::text('facebook', Auth::user()->redessociais()->first()->facebook, ['class' => 'form-control input-md' , 'placeholder' => 'Facebook']) !!}
        </div>
    </div>

    <div class="row" style="margin-bottom: 20px; margin-top: 30px;">
        <div class="col-md-3 col-lg-3"></div>
        <div class="col-md-9 col-lg-9">
            {!! Form::submit('Alterar redes sociais', ['class' => 'btn btn-primary']) !!}
        </div>
    </div> 
{!! Form::close() !!}

Upvotes: 1

Views: 192

Answers (3)

patricus
patricus

Reputation: 62228

In addition to the other two answers provided, the other issue is that you have a call to first() inside your redessociais() method. In your blade file, you're then calling first() again on that result.

So, if there is no associated record, Auth::user()->redessociais() will return null (since it has already called first()), and then you're calling first() again on null.

If redessociais() is meant to be a relationship method, it should not call first(). It should be defined as:

public function redessociais(){ 
    return $this->hasMany('App\RedesSociais','id_user','id');
}

Upvotes: 0

Eduardo Pacios
Eduardo Pacios

Reputation: 1865

When you use find(), it returns an Eloquent object if a record is found, otherwise returns null. So, if you use find()->first() it will work okay only when a record is found. If not found, you get null, and you can't do null->first(). That's what the error is saying. The solution is to check like this:

if($user = RedesSociais::find(Input::get('id'))) {
    $user -> update($redesociais);
}else{
    $user = RedesSociais::insert($redesociais);
}

You can also check if(!is_null(RedesSociais::find(Input::get('id'))))

Upvotes: 1

djt
djt

Reputation: 7535

The error means that the object on which you're calling first() -- in this case, RedesSociais::find(Input::get('id')) -- is NULL. So it seems that this record does not exist in your RedesSocials model.

Try adding dd(Input::get('id')) somewhere before this line to check which ID your Controller is actually receiving. Then check if this ID is in your database.

Upvotes: 0

Related Questions