Difficulty with belongingto Laravel 5.6

0

Good evening. I'm doing a project with Laravel and I'm having a difficult relationship Could you help me?

I have two entities in my bank that are Student and Situation.

Student has these attributes: id, name, string, email. Situation has these attributes: id, name_situation.

The relationship is from 1 to N. And the primary key of the table Situation goes to the student table as a foreigner.

I'm doing this in Laravel 5.6 and in the student's registry I'm not getting popular a select pulling his situation that would be these three: Enrolled, Bag, Defaulter.

I saw in Laravel's doc that in this case it would be necessary to use the belongsto, but I did not understand that right. I'll post the two models, the controller and the view.

--- STUDENT MODEL ---

<?php

namespace App\Models\Escola;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Aluno extends Model
{
    protected $fillable = [
        'nome', 'serie', 'email', 

    ];     

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

--- SITUATION MODEL ---

<?php

namespace App\Models\Escola;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Situacao extends Model
{
     protected $fillable = [
        'nome_situacao'
    ];
    protected $table = 'situacoes';


    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

- THIS IS THE CONTROLLER

<?php

namespace App\Http\Controllers\Escola;

use Validator; 
use App\Models\Escola\Aluno;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class AlunoController extends Controller{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $alunos = Aluno::latest()->paginate(10);

        return view('escola.alunos.index',compact(
            'alunos', 'nome', 'serie', 'email'))
            ->with('i', (request()->input('page', 1 ) -1) * 5);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */


    public function store(Request $request)
    {
        request()->validate([
            'nome' => 'required',
            'serie' => 'required',
            'email' => 'required',


        ]);

        Aluno::create($request->all());

        return redirect()->route('alunos.index')
                    ->with('success', 'Aluno cadastrado com sucesso!');

    } 

}

- MY VIEW -

@extends('adminlte::page')

@section('title', 'Cadastro')

@section('content_header')
    <center>
    <br>
    <h3 style="margin-top: -30px;">Gerenciador de Alunos</h3>
    </center>
@stop

@section('content')
<br>
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-right">
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-success" data-toggle="modal" data-target=" .bd-example-modal-lg">Incluir Aluno</button>
            </div>

            <!-- Modal -->
            <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
              <div class="modal-dialog modal-lg">
                <div class="modal-content">

                <form action="{{ route('alunos.store') }}" method="POST">
                    @csrf
                    <div class="container box box-success">
                <br>
                <div class="row">
                    <div class="col-md-4">
                        <strong>Nome do Novo Aluno:</strong>
                            <input type="text" name="nome" class="form-control" placeholder="Digite o nome..." required="ON">
                    </div>

                <div class="col-md-4">
                        <strong>Serie do Novo Aluno:</strong>
                            <input type="email" name="serie" 
      class="form-control" placeholder="Digite o nome..." required="ON">
                    </div>

                    <div class="col-md-4">
                        <strong>Email do Novo Aluno:</strong>
                            <input type="email" name="email" class="form-control" placeholder="Digite o email..." required="ON">
                    </div>

<div class="row">
                        <div class="col-md-4">
                            <strong>Selecione a Situação</strong>
                            <select name="situacao_id" class="form-control" required="ON">
                            <option value="">Clique aqui</option>

                            @foreach ($classsituacao_array as $situacoes_id)
                                <option value="{{$situacoes_id->id}}" > {{$situacoes_id->nome_situacao}}</option>
                            @endforeach 
                            </select>    

                        </div>
<div class="row">
                        <div class="col-md-4">
                        </div> 

                        <div class="col-md-4">
                        <center><button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button></center>
                        </div>

                        <div class="col-md-4">
                            <button type="submit" class="btn btn-sic btn-success btn-block btn-flat ">

                            Enviar</button>
                        </div>
                    </div>
                    <br>
                </form>
                </div>   
              </div>
            </div>
            </div> 
        </div>
    </div>
            <!--Mensagem de sucesso ao cadastrar-->

        @if ($message = Session::get('success'))

            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>

       @endif

    <head>

        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

        <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script><scripttype="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script><scripttype="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script><scripttype="text/javascript" class="init">

            $(document).ready(function() {
            $('#tobarril').DataTable({
                    "language": {
                    "lengthMenu": "Visualizando _MENU_  itens por página",
                    "zeroRecords": "Item não encontrado",
                    "info": "Visualizando página _PAGE_ de _PAGES_",
                    "infoEmpty": "Nenhum item a ser exibido",
                    "infoFiltered": "(Filtrado from _MAX_ total records)"
                        }
                    } 
                );
            } );
        </script>

    </head>

    <br>
    <div class="container box box-success">
    </div>
    <br>
        <table id="tobarril" class="table table-bordered"> 

        <thead>
        <tr>
            <th><center>Nome</center></th>
            <th><center>Serie</center></th>
            <th><center>Email</center></th>
            <th><center>Situacao</center></th>
            <th width="150px"><center>Ação</center></th>
        </tr>
        </thead>
        @foreach ($alunos as $aluno)
        <tbody>
        <tr>
            <td><center>{{ $aluno->id }}</center></td>
            <td><center>{{ $aluno->nome }}</center></td>
            <th><center>{{ $aluno->serie }}</center></th>
            <th><center>{{ $aluno->email }}</center></th>
            <th><center>{{ $aluno->situacao }}</center></th>



 <center>
                <form action="{{ route('alunos.destroy',$aluno->id) }}" method="POST">



                    <a class="btn btn-primary" href="{{ route('alunos.edit',$aluno->id) }}">Editar</a>


                    @csrf
                    @method('DELETE')


                    <button type="submit" class="btn btn-danger">Deletar</button>
                </form>
            </center>
            </td>
        </tr>
        </tbody>
        @endforeach
    </table>


   {!! $alunos->links() !!}



@endsection

What I'm doing is returning the id of the situation in the view, but I wanted it to inform the record of the situation (Enrolled, Scholar, Defaulter). I was able to do this using Providers, but it is not the correct way of popular or select, because if for example I take from the view the stock market situation it sum of the select, when it should be in the bank. That is, in that way it populates the select according to what I keep in the view of the Situation Crud.

Can anyone give this strength there?

    
asked by anonymous 13.09.2018 / 01:31

1 answer

0

If the student can have several situations then "student hasMany (has many) situation", and "situation belongsTo" student, remembering that it is necessary to carry out the mapping of both sides so that it works the way expected.

Here are some examples of relationships in models:

Student Class

  

public function situation () {

     

return $ this-> hasMany (Situation :: class);

     

}

Class Location

  

public function student () {

     

return $ this-> belongsTo (Student :: class);

     

}

    
19.09.2018 / 20:30