Laravel

169

Solutions

144

Contributors

Laravel is a free, open-source PHP web application framework for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar. Laravel is regarded as one of the most popular PHP frameworks.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts

Could you point what is needed to be adjusted at this Laravel code to correctly call the Controller method?

The link is at the site's main page:

img003
@if($vitrinesX->count()>0)
	 <div class="col-md-12">
	 
		<img src="{{ $vitrinesX[0]->url }}" />
		<br />
		 
		 
		 <div class="col-md-12" style="padding-top: 9px;">
			
			<a href="/vitrine?id={{ $vitrinesX[0]->id }}">
				ver todas as fotos
			</a>
			<br />
			
			<!-- Route that must to be called -->
			<a href="/vitrine/minhasfotos">
				ver minhas fotos
			</a>
			 <br />
			
		</div>
	</div>

@else
	<div class="col-xs-12 col-sm-12 col-md-12">
		<div class='alert alert-info'>
			Nenhuma vitrine cadastrada, ativa ou aprovada.
		</div>
	</div>
@endif

Open in new window



Route:
Route::get('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');

Open in new window


Then a 2nd page must to be oppened with only the images owned by the logged user.


The Controller is not called.

Thanks in advance.
0
Hi Experts

Could you point how to refresh data at a Laravel view when data to be presented changes ?

When the page is initially presented it shows all the images.

Then a filter is applied and the collection to be presented is much smaller. The view is called the same way it was for all the images, but the images presented are not actualized.

If the view is started with the data filtered it's correctly presented.

Thanks in advance.
0
Hi Experts


Could you point what must to be adjusted at this Laravel Eloquent code to filter only the elements from "Vitrine" that belongs to the logged user_id?

Accordingly to:
img014

My attempt (incorrect) was

$vitrinesX = Vitrine
			::with('user_vitrine')
			->ativa()
			->aprovada()
			->global(Auth::user()->tipoparticipante_id)
			->orderBy('id','desc')
			->withCount([
				'user_vitrine as qtdeCurtiu' => function (Builder $query) { $query->where('curtiu', 1); },
			])
			->where('user_id', auth()->user()->id)
			->paginate(3);

Open in new window



Thanks in advance
0
Hi Experts

Could you point why a Laravel Controller method produces an error when another similar runs correctly?

Accordingly to:

JS
function Vitrine() {}
 

//OK
Vitrine.prototype.salvar = function(){
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};


// This doesn't runs correctly
Vitrine.prototype.minhasfotos = function(){
  $.ajax({
    url: '/vitrine/minhasFotos',
    method: "GET",
    dataType: "html",
    error:function(data){
      hotsite.openModalCustom("Erro", "Erro ao carregar vitrine.", "Entendi", "error");
    },
    success: function(data){
      $('#midiaList').html(data);
    }
  });
}

Open in new window



Laravel routes:
Route::post('/vitrine/salvar',['uses'=>'VitrinesController@salvar'])->middleware('cadastro');   // OK
Route::post('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');  //NOK

//This route apparently is called somehow....
Route::get('/vitrine/{id}/obter',['uses'=>'admin\VitrineController@obter'])->middleware('cadastro');

Open in new window



VitrinesController methods:

Open in new window

0
Hi Experts


Could you point how to configure this Bootstrap buttons to be correctly distributed accordingly with this layout?

img010

<div class='row'>

      <div class="panel panel-primary">
      
          <div class='row'>
          
            <div class='col-md-8 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Minhas Fotos
                </button>
              </div>
            </div>
            
            <div class='col-md-6 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Todas as Fotos
                </button>
              </div>
            </div>
              
            <div class='col-md-4 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Enviar Foto
                </button>
              </div>
            </div>
              
          </div>  
       
    </div>
</div>

Open in new window


Thanks in advance!
0
Hi Experts


Could you point what's needed to change from video upload to image/photo upload on this view?

Accordingly to this code:

<div id='box-video' class='col-md-5 text-center'>

	<video controls style='width: 100%'>
		<source id='srcVitrine' src='' />
	</video>
	
	// Change to:
	<img controls style='width: 100%'>
		<source id='srcVitrine' src='' />
	</img>
	

	<div class='col-md-12 form-group'>
		<label for='titulo'>URL (Vídeo):</label>
		<div class="input-group">
			<input type='text' id='url' name='url' disabled class='form-control'/>
			<span class="input-group-btn">
				<button class="btn btn-primary" type="button" onclick='hotsite.vitrine.subirVideo();'><i class="fa fa-camera"></i></button>
			</span>
			<input type='file' id='file' name='file' style='display:none;'/>
		</div>
	</div>
</div>


<script>
  var jqXHRData;
  $(document).ready(function() {

    
    var pars = {
        _token:$('input[name="_token"]').val()
    };

    var resultImageUpload = function (data) {
        if (!data.result.erro) {
            localizacao = data.result.retorno.localizacao;
            $('#url').val(localizacao);
            $('#srcVitrine').attr('src', localizacao);
            
			
			// This runs
			$("#box-video video")[0].load();
			
			// This doesn't run
            $("#box-video img")[0].load();
					
            return false;
        } else {
          hotsite.openModalCustom("Erro",'Erro ao subir vídeo.', "Entendi", "error");
          return false;
 

Open in new window

0
Hi Experts

Could you point how to correctly use Laravel's paginate method at this code?

    $vitrinesX = Vitrine
           ::with('user_vitrine')
	   ->ativa()
	->aprovada()
	->global(Auth::user()->tipoparticipante_id)
	->orderBy('id','desc')
	->withCount([
		'user_vitrine as qtdeCurtiu' => function (Builder $query) { $query->where('curtiu', 1); },
		//'user_vitrine as naocurtiu' => function (Builder $query) { $query->where('curtiu', 0); }
	])
	->get()->paginate(5)
	->each(function($vitrine) {
		$vitrine->liked_by= $vitrine->user_vitrine->pluck('id');
	});

Open in new window


Produces this error:

img001
Thanks in advance.
0
I'm trying to get things done quick.

I'm working on a Laravel project, I realize I need to alter the structure of a table so I just go into phpMyAdmin, do what needs to be done and then alter the corresponding migration file.

You're not supposed to do that, are you?

In the interest of keeping the migration file current, I just changed the schema. But then I began to wonder if that wasn't going to throw things off systemically and now, things are all cornfused.

First of all, just for the sake of my own edification: Migrations are not optional. Regardless of how incremental of a change you're making to your database, it all has to be done through the migration dynamic because that's a part of the way Larevel / Eloquent are processing things, correct?

Secondly, for the sake of cleaning up the mess i just described, here's what I did:

I created a "drop_video_table" migration and ran that successfully.
Here's the "create_videos_table" migration that I edited (perhaps incorrectly)

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateVideosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->bigIncrements('id');
			$table->string('title');
			[b]$table->binary('description');
			

Open in new window

0
Hi Experts

Could you point why this HTML textarea is not actualized when changing the pictures since JS scripts shows it has changed?

Accordingly to:

 img002
What occurs is:
img003
Page Code:
  <div class="modal fade" id="mMidiaEditar" tabindex="-1" role="dialog" aria-labelledby="mMidiaEditarLabel">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="mMidiaEditarLabel">Mídia</h4>
        </div>
        <div class="modal-body">
          {{ csrf_field() }}
          <input type='hidden' id='id'/>
          <div class='form-group'>
            <label for='tituloEditar'>Título:</label>
            <input type='text' class='form-control' id='tituloEditar' name='tituloEditar'/>
          </div>

<!--  --->
          <div class='form-group'>
            <label for='descricaoEditar'>Descrição X:</label>
            <textarea class='form-control' id='descricaoEditar' name='descricaoEditar' rows="5"></textarea>
          </div>
<!--  --->

          <div class='form-group'>
            <label for='tipoparticipanteEditar'>Perfil:</label>
            <select id='tipoparticipanteEditar' name='tipoparticipanteEditar' class='form-control'>
              <option value='0'>Para todos os 

Open in new window

0
Hi Experts

Could you point a eay to present a photo by giving its url location by using PHP/ Laravel?

Accordingly with

<div class="box-noticias">
	<a href="javascript:void(0);" onclick='....;' >
	{{$vitrine->url}}
	</a>                    
</div>

Open in new window


Actually the{{$vitrine->url}}  presents the url itself, something like:

https://xxxxx.blob.core.windows.net/xxx/vitrines/87w91898.BMP

So I need to render it to show as a image.

Thanks in advance.
0
I'm creating a table in Laravel. I created both my Model and my Migration using:

php artisan make:model Video -m

That resulted in a new Migration file called, "2020_02_13_023156_create_videos_table.php" which looks like this:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateVideosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->bigIncrements('id');
			$table->string('title');
			$table->binary('code');
            $table->timestamps();
        });
    }

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

Open in new window


Perfect!

Now, I want to add that table to the database, so I run this:

$ php artisan migrate --path=database/migrations/2020_02_13_023156_create_videos_table

...and I get an error that says, "Nothing to migrate."

So, I'm looking at what appears to be a sound approach, but there's no "videos" table in the databsae.

What am I missing?
0
Hi Experts

Could you point why a Controller method code is subtly returning to a jquery ajax without running and returning OK to JS ?

Accordingly to:

Vitrine.prototype.salvar = function(){
    
  console.log ('JS salvar');
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};

Open in new window


and Controller method:


 public function salvar(Request $request){
   
	 //Forcing an error
	 //aaa;
	
	
	// Otherwise subtly exit with no traces.
	info('xxx');
   
	dd('aaa');

	$id=$request->input('id');
	$url=$request->input('url');
	$inicio=$request->input('inicio');
	$termino=$request->input('termino');

	$titulo = $request->input('title');
	$descricao = $request->input('description');
	$pontuacao = $request->input('points');

	try{
		if($id != '' &&  $id > 0){
		  $vitrine = Vitrine::find($id);
		}

		if(empty($vitrine)){
		  $vitrine = new Vitrine();
		  $vitrine->created_at=new \DateTime();
		}
			
		$vitrine->title = $titulo;
		$vitrine->description = $descricao;
		$vitrine->points = CustomFuncs::brancoParaNulo($pontuacao);
		$vitrine->url = $url;
		$vitrine->validity_start = empty($inicio) ? null : CustomFuncs::formatarDataUS($inicio);
		$vitrine->validity_end = empty($inicio) ? null : CustomFuncs::formatarDataUS($termino);
		$vitrine->updated_at=new \DateTime();
		
		info($vitrine);
		
		
		$vitrine->save();

	} catch (\Exception $e) {
		return response()->json(new Resultado(true,'','Erro ao salvar o vídeo'), 400);
	}

	return response()->json(new Resultado(false,'','Vídeo cadastrado com sucesso'));

}

Open in new window



The forced error:

img015
Thanks in advance!
0
Hi Experts


Could you clear why this Controller method isn't called as expected?

Accordingly with a previous question this form have 02 phases

1st: Upload a picture to a defined path - In my tests by using  
use Illuminate\Support\Facades\Storage;

Open in new window

It's perfectly locally uploaded.


2nd  The image url and details must to be saved at the table Vitrines

So, this method is called

Vitrine.prototype.salvar = function(){
    
  console.log ('JS salvar');  // Pass here
  
  $.ajax({
    url: '/admin/vitrine/salvar',
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};

Open in new window


img008
This method is configured at routes

Route::post('/admin/vitrine/salvar',['uses'=>'admin\VitrineController@salvar'])->middleware('cadastro');

Open in new window


But it doesn't seen it's called at VitrineController

 public function salvar(Request $request){
 
       

Open in new window

0
Hi Experts

Could you give me directions on how this JS uploading photo method is running?

-- web page script

<script>
  var jqXHRData;
  $(document).ready(function() {
    ZZZsite.video.filtrar();
    var pars = {
        _token:$('input[name="_token"]').val()
    };

    var resultImageUpload = function (data) {
        if (!data.result.erro) {
            localizacao = data.result.retorno.localizacao;
            $('#url').val(localizacao);
            $('#srcVideo').attr('src', localizacao);
            $("#box-video video")[0].load();
            return false;
        } else {
          ZZZsite.openModalCustom("Erro",'Erro ao subir vídeo.', "Entendi", "error");
          return false;
        }
    };

    var failImageUpload = function (data) {
          if (data.files[0].error) {
              ZZZsite.openModalCustom("Erro",'Erro ao subir vídeo.', "Entendi", "error");
              return false;
          }
    };

// --- DOES THIS PART ASKS TO SAVE ON A PATH (???)
    ZZZsite.InitFileUpload("file", "/admin/videos/salvarVideo", pars, resultImageUpload, failImageUpload);
//----------------------------------------


    $("#file").change(function () {
        if (jqXHRData) {
            jqXHRData.submit();
        }
        return false;
    });
  })
</script>

Open in new window



-- JS script
ZZZsite.prototype.InitFileUpload = function(
  input,
  url,
  pars,
  doneCallbackFunction,
  failCallbackFunction
) {
  "use strict";

  $("#" + input).fileupload({
    url: url,
    formData: pars,
    dataType: "json",
    type: "POST",
    add: function(e, data) {
      jqXHRData = data;
    },
    done: function(event, data) {
      if (
        doneCallbackFunction != undefined &&
        typeof doneCallbackFunction == "function"
      ) {
        doneCallbackFunction(data);
      } else {
        ZZZsite.openModalCustom("Erro", data, "Entendi", "error");
      }
    },
    fail: function(event, data) {
      if (
        failCallbackFunction != undefined &&
        typeof failCallbackFunction == "function"
      ) {
        failCallbackFunction(data);
      } else {
        ZZZsite.openModalCustom("Erro", data, "Entendi", "error");
      }
    }
  });
};

Open in new window



img001



At VideoController I found the method SalvarVideo ... (called at the page)

   public function salvarVideo(Request $request){
        $video=$request->file('file');

        if (!$request->hasFile('file')){
            $resultado=new Resultado(true,"","Nenhum arquivo foi selecionado.");
            return response()->json($resultado);
        } else {			
            $videoUrl = AzureStorage::saveFile($video,'videos');
        }

        $output = array(
            "localizacao" => $videoUrl,
        );

        $resultado=new Resultado(false,"",$output);

        return response()->json($resultado);
    }

Open in new window


After choosing a photo the textbox is filled with a location very unclear.

Since I'm still developing and need to test it, the correct here is to create a defined path to save the photo image file?

Thanks in advance!
0
Hi Experts


Could you point a way to avoid an user to vote more than one time at each picture on this Laravel view?

    <input type="hidden" id="hdnCurtiu" value="{{$curtiu}}">

        <div class="col-md-12 col-sm-12">

                <section class="row">
               
                        @foreach($vitrinesX->chunk(3) as $row)
                        
                            @foreach($row as $vitrine)
          
                          
                               <div class="col-sm-12 col-md-4">
                               
                                    @php 
                                        $currentUserId = auth()->user()->id;
                                        $hasUserVoted = $vitrine->liked_by->contains($currentUserId); 
                                    @endphp
                               
                                    <div class="box-noticias">
                                       	<a href="javascript:void(0);" onclick='hotsite.vitrine.abrirVitrine({{$vitrine->id}});' >
                	    				{{$vitrine->titulo}}
                	    			    </a>                    
                                    </div> 
                                    
                                    <p id="like" class="likes" @if (!$hasUserVoted ) onclick="hotsite.vitrine.salvarEscolha({{ $vitrine->id }}, 1)" @endif>
                                        <i class="fa fa-thumbs-up"></i> <span id="qtdeCurtiu_{{ $vitrine->id

Open in new window

0
Hi Experts

Could you point a way to enable/ disable an "Like"  icon depending on the user had clicked on it before or not - considering on an available collection of data?


img014


Giving this actual Laravel running  view code:

	<div class='row'>


	{{ csrf_field() }}
    <input type="hidden" id="hdnCurtiu" value="{{$curtiu}}">

        <div class="col-md-12 col-sm-12">

                <section class="row">
               
                        @foreach($vitrinesX->chunk(3) as $row)
                        
                            @foreach($row as $vitrine)
                            
                            
                              @php $hasUserVoted = $vitrine->liked_by->contains($vitrine->id);
                              
                                    info($vitrine->linked_by);
                               @endphp
                          
                               <div class="col-sm-12 col-md-4">
                               
                               
                                    <div class="box-noticias">
                                       	<a href="javascript:void(0);" onclick='hotsite.vitrine.abrirVitrine({{$vitrine->id}});' >
                	    				{{$vitrine->titulo}}
                	    			    </a>                    
                                    </div> 
                                    
                                   	<p id="like" class="likes" 

Open in new window

0
Hi Experts


Could you point a way to enable/ disable an like icon depending on the user had clicked the icon before or not?

Accordingly with:

img004
The user has the right of click the "Like" of  a photo once and after that he coudn't do nothing else, the like icon must to be disabled.
If the user reenter the page the like icon for the photo that had received a "like" must to stay disabled, also, by using the user's id.

The actual view:

@extends('layouts.appinterno')

@section('content')

	<div class='row'>

	{{ csrf_field() }}
    <input type="hidden" id="hdnCurtiu" value="{{ $curtiu }}">

        <div class="col-md-12 col-sm-12">
               
                <section class="row">
               
                        @foreach($vitrinesX->chunk(3) as $row)
                        
                            @foreach($row as $vitrine)
                          
                               <div class="col-sm-12 col-md-4">
                               
                                    <div class="box-noticias">
                                       	<a href="javascript:void(0);" onclick='xxx.vitrine.abrirVitrine({{$vitrine->id}});' >
                	    				{{$vitrine->titulo}}
                	    			    </a>                    
                                    </div> 
                                    
                                   	<p id="like" class="likes" onclick="xxx.vitrine.salvarEscolha({{ $vitrine->id 

Open in new window

0
Hi Experts


Could you point how to adjust this Laravel Controller/ Model code to correctly obtains data from these 02 tables?

Accordingly to:
img004

Actual Controller code:
 $vitrinesX = Vitrine
                ::vigente()
                ->ativa()
                ->aprovada()
                ->global(Auth::user()->tipoparticipante_id)
                ->orderBy('id','desc')
                ->get();

Open in new window


It obtains data just for the table Vitrines.

What is needed is to obtain a sum() of column curtiu at the associated table User_vitrines.

In a way that the resultant query presents the actual data plus two other columns that are  the sum(curtiu=0)  and sum (curtiu=1)

The Model Vitrine code is:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\User;
use Carbon\Carbon;

class Vitrine extends Model
{
  public function tipoparticipante(){
      return $this->belongsTo('App\Models\Tipoparticipante');
  }

  public function criador(){
    return $this->belongsTo('App\User', 'criador_id', 'id');
  }

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

  public function scopeTitulo($query,$value){
    if ($value===''){
      return $query;
    } else {
      return $query->where('titulo','like','%'.$value.'%');
    }
  }

  public function scopeConteudo($query,$value){
    if ($value===''){
      return $query;
    } else {
      return 

Open in new window

0
Hi Experts

Could you point why this Laravel view code doesn't correctly actualize the icons like/ dislike on the correct position after click?

Accordingly with:
 img004
Even clicking on the 2nd or 3rd like/ dislike icons only the count at the icon side of the 1st picture are (incorrectly) actualized.

The views code:
@extends('layouts.appinterno')

@section('content')

	{{ csrf_field() }}
	<input type="hidden" id="hdnCurtiu" value="{{ $curtiu }}">


  	  	<!--div class="col-xs-12 col-sm-4 col-md-4"-->
        <div class="col-md-10 col-sm-12">
		    <p class="titResumoNoticia">Arquivo de Fotos</p>
		   
   
            @foreach($vitrinesX as $vitrine)

                <section class="row">
        
        
                        <div class="col-sm-12 col-md-4">
                            <div class="box-noticias">
                               	<a href="javascript:void(0);" onclick='hotsite.vitrine.abrirNoticia({{$vitrine->id}});' >
        	    				{{$vitrine->titulo}}
        	    			    </a>                    
                            </div>
                            
                            	<p id="like" class="likes" onclick="hotsite.vitrine.salvarEscolha({{ $vitrine->id }}, 1)">
				                    <i class="fa fa-thumbs-up"></i> <span id="qtdeCurtiu">{{ $qtdeCurtiu }}</span>
				               	</p>   
                                    
           						<p id="dislike" class="likes" 

Open in new window

0
Hi Experts


Could you point how to adapt this PHP/ Bootstrap code to correctly format the desired layout?

Accordingly with this code:

@extends('layouts.appinterno')

@section('content')

	<div class='row'>

	{{ csrf_field() }}

  	  	<!--div class="col-xs-12 col-sm-4 col-md-4"-->
        <div class="col-md-10 col-sm-12">
		    <p class="titResumoNoticia">Arquivo de Fotos</p>
		   
     
            @foreach($vitrinesX as $vitrine)

                <section class="row">

                               
                        <div class="col-sm-12 col-md-4">
                            <div class="box-noticias">
                               	<a href="javascript:void(0);" onclick='xxx.vitrine.abrirNoticia({{$vitrine->id}});' >
        	    				{{$vitrine->titulo}}
        	    			    </a>                    
                            </div>
                            
                            	<p id="like" class="likes" onclick="xxx.vitrine.salvarEscolha({{ $vitrine->id }}, 1)">
				                    <i class="fa fa-thumbs-up"></i> <span id="qtdeCurtiu_{{ $vitrine->id }}">{{ $qtdeCurtiu }}</span>
				               	</p>   
                                    
           						<p id="dislike" class="likes" onclick="xxx.vitrine.salvarEscolha({{ $vitrine->id }}, 0)">
				                    <i class="fa fa-thumbs-down"></i> <span id="qtdeNaoCurtiu_{{ $vitrine->id }}">{{ $qtdeNaoCurtiu }}</span>
						       </p>       
                        </div>     

Open in new window

0
I need to pass two entities into my view. Both of which work fine when I retrieve them one at at time, but I'm blowing it somewhere when I try to do both.

Here's the function I'm wrestling with in my Controller and my attempt to pass both sets of data into my route simultaneously:

	public function professionals($id) {
		$pages = Page::findOrFail($id);
		$pros = Professional::sortable()->orderBy('lname', 'asc')->paginate(25);
		return view('pros', compact('pros'))->with('pages', compact('pages'));
	}

Open in new window


Here's my view:

@extends('layouts.satellite')
@section('content')
<!-- Section: intro -->
<section id="intro" class="intro">
	<div class="satellite-content">
		<div class="container">
			<div class="row">
				<div class="col-xs-12 satellite_row">
					<?php echo $pages->body; ?>
					<table class="table table-bordered">
						<tr>
						<td style=" background-color:#ea7fea; color:#fff; text-align:center; font-weight:bold;">#</td>
							<td style=" background-color:#ea7fea; color:#fff; text-align:center; font-weight:bold;">@sortablelink('lname', 'Name') </td>
							<td style=" background-color:#ea7fea; color:#fff; text-align:center; font-weight:bold;">@sortablelink('discipline', 'Discipline')</td>
							<td style=" background-color:#ea7fea; color:#fff; text-align:center; font-weight:bold;">@sortablelink('country', 'Country')</td>
							<td style=" background-color:#ea7fea; color:#fff; text-align:center; 

Open in new window

0
I migrated a table from another database into a Laravel application.

First of all, it looks like all Laravel tables include a "created_at" and an "updated_at" column that need to be added in order for any kind of update or insertion to occur without an error, yes?

I'm assuming that's the case.

So, here's what I attempted to do for a migration that added those timestamps:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AlterProfessionalTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
		Schema::table('professionals', function (Blueprint $table) {
            //
			$table->timestamps();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
		$table->dropTimestamps();
    }
}

Open in new window



I got this error:

   Symfony\Component\Debug\Exception\FatalThrowableError  : syntax error, unexpected 'public' (T_PUBLIC), expecting ')'

  at C:\wamp64\www\new_nomas\database\migrations\2020_01_31_205053_alter_professional_table.php:27
    23|      * Reverse the migrations.
    24|      *
    25|      * @return void
    26|      */
  > 27|     public function down()
    28|     {
    29|         //
    30|                 $table->dropTimestamps();
    31|     }


Where did I blow it?
0
Hi  Experts


Could you point how to correctly reuse an existent view as a template for another by using Laravel?

The view I already have:
<section class='row'>

	<div class="col-md-12 titulo">Notícias</div>
	@if($noticias->count()>0)
		<div class="col-md-12">
			<img src="{{ $noticias[0]->url }}" />
			<h4>{{ $noticias[0]->titulo }}</h4>
			<a href="/noticia?id={{ $noticias[0]->id }}">
				leia mais
			</a>
            
            <br />
           	<a href="/noticia?id={{ $noticias[0]->id }}">
				ver todas
			</a>  

		</div>
	
	@else
		<div class="col-xs-12 col-sm-12 col-md-12">
			<div class='alert alert-info'>
				Nenhuma notícia cadastrada, ativa ou aprovada.
			</div>
		</div>
	@endif

	<script src="{{ asset('js/hotsite/Hotsite.Noticia.js').'?v='.md5(uniqid()) }}" ></script>
<section>

Open in new window


It uses the table noticias


To get another similar view to have a similar functioality I created the table "vitrine" (directly at MySQL, without using migrations) and then created that another view:
<section class='row'>


	<div class="col-md-12 titulo">Instagaz</div>
	@if($vitrine->count()>0)
		 <div class="col-md-12">
			<img src="{{ $vitrine[0]->url }}" />

             <div class="col-md-12" style="padding-top: 9px;">
    			<a href="/vitrine?id={{ $vitrine[0]->id }}">
    				ver todas as fotos
    			</a>
                <br />
               	<a href="/vitrine?id={{ $vitrine[0]->id }}">
    				ver minhas fotos
    			</a>
                 <br />
                <a href="/vitrine?id={{ $vitrine[0]->id }}">
    				enviar minha foto
    			</a>
                
    		</div>
        </div>
 
	@else
		<div class="col-xs-12 col-sm-12 col-md-12">
			<div class='alert alert-info'>
				Nenhuma vitrine cadastrada, ativa ou aprovada.
			</div>
		</div>
	@endif

	<script src="{{ asset('js/hotsite/Hotsite.Noticia.js').'?v='.md5(uniqid()) }}" ></script>
<section>

Open in new window



And then created Model and Controller correspondent to "Vitrine"

But when running it that error occurs:

 img014
I couldn't find the count() method count() declared - just used on the code.... is that an Eloquent method?

If any aditional code is needed to better question's comprehension just say it.

Thanks in advance.
0
Here's the counsel I'm attempting to implement:

Here's the counsel that I'm attempting to implement:

One other thing of note. Regardless of whether your password is validated or not, the request will still contain the password field. What this means is that if you don't fill in the password (and it skips the validation part), then your request will be valid, but the input->password will be NULL. You obviously don't want to be inserting that into the database:

$user->password = Hash::make($request->input('password'));

What you should be doing is looking at the validated data, and not the request data. In your controller, add this line:

$validated = $request->validated();

Now the $validated array will only contain data that passed validation. If you skipped validating the password, then it won't exist in that array:

if (isset($validated['password'])) {
    $user->password = Hash::make($validated['password']);
}

Hope that all makes sense. Like I said, quite a few moving parts to this, including some Laravel 'magic'.

When I go to update my user with a new password, this is the Controller that's being utilized:

public function update(UpdateUserRequest $request)
    {
       [b]$validated = $request->validated();[/b]
       $user=User::findOrFail($request->the_id);
	   if($request->input('admin_yes')=="Y") {
			$user->admin=1;
		}
		else {
			$user->admin=0;
		}
		if($request->input('update_pass')==1) { // we're updating the 

Open in new window

0
Hi Experts

Does Laravel has a way to automatize queries to generate the Eloquent code?

I mean a tool to  grafically makes the joins and then to obtain the correspondent Eloquent code.

Thanks in advance.
0

Laravel

169

Solutions

144

Contributors

Laravel is a free, open-source PHP web application framework for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar. Laravel is regarded as one of the most popular PHP frameworks.

Top Experts In
Laravel
<
Monthly
>