Problems listing data from related tables in Laravel 5.3?

Asked

Viewed 1,131 times

1

I’m working with php, Laravel 5.3 and myql. Having created everything (Migration, model,controller, View, relationship), is giving me the following error:

Errorexception in 1d01653e0e29121ce444ef5c2072fb4d52e5e7db.php line 12: Trying to get Property of non-object (View: C: xampp htdocs Projecto5_3 Resources views products index.blade.php)

But when I remove the line view

 <p style="color: #069">{{ $produto->categs->nome_cat }}</p>

appear only the product table data. How to solve this problem?

Code.

Migration categs

class CreateCategsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categs', function (Blueprint $table) {
            $table->increments('id');
            $table->text('nome_cat');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categs');
    }
}

Migration products

class CreateProdutosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('produtos', function (Blueprint $table) {

            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->text('nome');
            $table->text('descricao');
            $table->unsignedinteger('categs_id');
            $table->timestamps();

            $table->foreign('categs_id')->references('id')->on('categs');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('produtos');
    }
}

Model categs

namespace App;

use Illuminate\Database\Eloquent\Model;

class categ extends Model
{
    //Relacionamento 1:n Categoria dos produtos

    public function produtos()
    {
        return $this->hasMany('App\produtos');
    }
}

Model products

namespace App;

use Illuminate\Database\Eloquent\Model;

class Produtos extends Model
{
    //
    public function categoria()
    {
        return $this->belongsTo('App\categs');
    }
}

Product controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Produtos;

class ProdutosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $produtos = Produtos::all();
        return view('produtos.index',['todosprodutos'=>$produtos]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('produtos.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'nome' => 'required',
            'descricao' => 'required'
            ]);

        $produtos = new Produtos;
        $produtos->nome = $request->nome;
        $produtos->descricao = $request->descricao;
        $produtos->id_cat = $request->id_cat;
        $produtos->save();

        return redirect('produtos')->with('message', 'Produto gravado com sucesso!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $produtos = Produtos::find($id);
        if(!$produtos)
            {abort(404);}
        return view('produtos.details')->with('detailpage',$produtos);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $produtos = Produtos::find($id);
        if(!$produtos)
            {abort(404);}
        return view('produtos.edit')->with('detailpage',$produtos);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'nome' => 'required',
            'descricao' => 'required',
        ]);

        $produtos = Produtos::find($id);
        $produtos->nome = $request->nome;
        $produtos->descricao = $request->descricao;
        $produtos->save();
        return redirect('produtos')->with('message', 'Produto actualizado com sucesso!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $produtos = Produtos::find($id);
        $produtos->delete();
        return redirect('produtos')->with('message', 'Produto excluido com sucesso!');
    }
}

View product - index

@extends('novomaster')
{{ Session::get('message') }}
@section('left-sidebar')
<h1 style=" color: #069">Produtos</h1>
<a class="btn btn-primary" href="produtos/create">Novo Produto</a>
<hr>

    @foreach($todosprodutos as $produto)
    <div class="alert alert-info" style="background-color:#C9DCFC">
        <h2><a href="/produtos/{{ $produto->id }}">{{ $produto->nome }}</a></h2>      
        <p style="color: #FFF">{{  $produto->descricao  }}</p>
        <p style="color: #069">{{ $produto->categs->nome_cat }}</p>
        <br />  


        <form action="/produtos/{{ $produto->id }}" method="POST">
            <input type="hidden" name="_method" value="delete">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <a class="btn btn-small btn-primary" href="/produtos/{{ $produto->id }}/edit"><i class="glyphicon glyphicon-edit"></i></a>

            <button class="btn btn-small btn-danger" type="submit" name="name" value="Apagar"><i class="glyphicon glyphicon-trash"></i></button>

       </form>
    </div> 
   @endforeach
@endsection

1 answer

1


In the model, as it was not default the key name, so you have to configure your model to receive this key in the configuration:

namespace App;

use Illuminate\Database\Eloquent\Model;

class categ extends Model
{
    //Relacionamento 1:n Categoria dos produtos

    public function produtos()
    {
        return $this->hasMany('App\Produtos', 'categs_id', 'id');
    }
}   

namespace App;

use Illuminate\Database\Eloquent\Model;

class Produtos extends Model
{
    //
    public function categoria()
    {
        return $this->belongsTo('App\categ','categs_id', 'id');
    }
}

now with the key settings and the interface, will work the data load for those relations. Another point is to observe: because categ whether the first letter should be uppercase, i.e., Categ, and the other model that is correct Produtos? the lack of pattern causes this confusion in the code, so follow the correct nomenclature all models starting with the first letter in uppercase, example Categoria, Produto, Cliente, etc and do not cut the name also instead of Categ place Categoria, in my view this greatly facilitates development and maintenance! , but, I did before what is in your question, are recommendations.


In the method of controller change, as example below:

public function index()
{
    $produtos = Produtos::with('categoria')->get();
    return view('produtos.index',['todosprodutos'=>$produtos]);
}

whereas the with will carry the relationship, and in its View change:

<p style="color: #069">{{ $produto->categoria->nome_cat }}</p>

Observing: the name that is in your relationship model is the same name as the method you were trying to access.!

References:

  • Thanks @Virgilio, I did it the way you suggested, that error disappeared and another one came up: Fatalerrorexception in Model.php line 779: Class 'App categs' not found. From what I’ve noticed, you’re not finding the class in this product model line: Return $this->belongsTo('App categs'); What do I do?

  • I realized that in this line "Return $this->belongsTo('App categs');" the name of the model is 'App categ' and not 'App categs', yet it continued error. In the view, I changed from: <p style="color: #069">{{ $product->category->name_cat }}</p>, to <p style="color: #069">{{ $product->category['nam_cat'] }}</p>, is not bringing the product category, it only brings data from the product table.

  • I tried the following on Tinker: $Prod=App Products::find(2), returned me the desired product. To know your categ, I did like this: $Prod->categ, returned to me NULL. After all, what is going on? What do I have to do? Please help me.

  • @Danieldossantos your code looking well has problems. I’ve seen what it is I’ll post in a little while wait I warn you already

  • @Danieldossantos I did the editing, not loaded due to lack of configuration of the relationship key, as you did not put pattern, should be informed in the parameters of belongsTo and hasMany, and the second part continues with the loading Produtos::with('categoria')->get(); it is optimized use it and check that the data has been returned. And guy take care with default, read the documentation of Laravel she is very rich and has all the details of the settings see my reply part Referencias

  • based on the above I did the following: In the Products model, Return $this->belongsTo('App categ','foreignKey'); and in the categ model, Return $this->hasMany('App products','foreignKey').

  • Look man this is how it is to work You must be doing something wrong, because this is in the documentation .... Check all your code @Danieldossantos

  • 1

    Another point is not foreingKey in the name of the relation is the name that corresponds by passing the 3 equal positions I put in the reply @Danieldossantos

  • It worked!!!!! Thank you very much @Virgilionovic for the help and recommendations he has left me. Thank you very much, God bless you.

  • The previous question has already been resolved. Now, it is giving me error when saving the product data, properly the foreign key categs_id in the database. You are giving the following error: SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'categs_id' cannot be null .

  • @Danieldossantos can open another question this has already been solved, each question generates a question and none or one or several answers . all right? open, put the controller, put what you’re doing and how did you get into this error

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.