We help IT Professionals succeed at work.

Laravel

195

Solutions

148

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.

Hi Experts

Could you point the better strategy to deploy a Laravel project at host ?

My hosting provider offers cPanel.

(I intend to do that to my own site)

Another option could be FTP - but I guess to transfer a complete Laravel project (with vendor folder) would be cumbesome to be done that way.

Thanks in advance.
0
Hi Experts      
            
Could you explain the meaning of this piece of Laravel code?

It was adapted from a legacy code due changes on table's structure.

      

		
$mes_atual = (int) date('m');	


        $compras = Compra::
                 leftjoin('periodos', 'periodos.id', 'compras.periodo_id')
                ->leftjoin('meses', 'periodos.mes', 'meses.mes')
                ->where('periodos.id', \DB::raw($mes_atual))
                ->groupBy('meses.id')
                ->select(DB::raw('(sum(grupo_a) + sum(grupo_b) + sum(grupo_c)  + sum(grupo_d) + sum(grupo_e) + sum(grupo_f) + sum(grupo_g)) as compraMensal'), 'meses.id')
                ->get();


        $totalDeMesesComCompra = $compras->count();

// What these parameters represents here?

$totalDeMesesComMetaBatida = $compras->reduce(function($quantidade, $item) use ($metasMensais){
  
  // This variable must to be redeclared here - otherwise it couldn't be found.... (?!)
  $mes_atual = (int) date('m');	

  $metaMes = $metasMensais
	  ->where('periodo_id', \DB::raw($mes_atual))
		->first();
		
	// The result of above query:
	// {"metaMensal":"139747.6600","periodo_id":2}
		
		
  if(empty($metaMes)){
	return $quantidade;
  }

  //   It results (1) if (true):  $metaMes->metaMensal >= $item->compraMensal 


  return $quantidade + ($metaMes->metaMensal >= $item->compraMensal);
}, 0);

Open in new window

           
            
            
		
$totalDeMesesComMetaBatida = $compras->reduce(function($quantidade, $item) use ($metasMensais){

  $metaMes = $metasMensais
			->where('mes', $item->mesreferencia)
			->where('ano', $item->anoreferencia)->first();
  
  
  if(empty($metaMes)){
	return $quantidade;
  }

  return $quantidade + ($metaMes->metaMensal >= $item->compraMensal);
}, 0);

Open in new window


Thanks in advance!
0
Hi Experts

Could you explain how an Laravel's Eloquent result could be used to operate another eloquent query?


This query:

$metasMensais = Distribuidormeta::

		  leftjoin('periodos', 'periodos.id', 'distribuidormetas.periodo_id')
		  
		  ->leftjoin('meses', 'periodos.mes', 'meses.mes')
		
		  ->where(function($q) use ($distribuidor_id, $distribuidorespermitidos_id){
			
			if($distribuidorespermitidos_id != null && count($distribuidorespermitidos_id) > 0){
			  $q->whereIn('distribuidor_id', $distribuidorespermitidos_id);
			}

			if($distribuidor_id != null && $distribuidor_id > 0){
			  $q->where('distribuidor_id', \DB::raw($distribuidor_id));
			}
			
		  })
		  ->where('periodos.mes', '>', \DB::raw(1))
		  ->where('periodos.id', \DB::raw($mes_atual))
		  ->groupBy('distribuidormetas.periodo_id')
		  ->select(DB::raw('sum(valor) as metaMensal'), 'periodo_id')  
		  ->get(); 

Open in new window



Results in:

[{"metaMensal":"139747.6600","periodo_id":2}]



After an Eloquent is aplied on the above result
$metaMes = $metasMensais
			->where('periodo_id', \DB::raw(2))
			->first();

Open in new window


But results in "null".

Is that correctly to use Eloquent this way?

Thanks in advance
1
So, I'm on vacation and wanted to work a little bit on a project I'm trying to wrap up.

I bring my project on a separate drive, install it in my WAMP directory and go to run "php aristan migrate" and this is what I get:

brucegust@BRUCEGUST7EFC MINGW64 /c/wamp64/www/new_nomas (bruce)
$ php artisan migrate

Parse error: syntax error, unexpected '?' in C:\wamp64\www\new_nomas\vendor\lara
vel\framework\src\Illuminate\Foundation\helpers.php on line 500

brucegust@BRUCEGUST7EFC MINGW64 /c/wamp64/www/new_nomas (bruce)
$ php -v
PHP 5.6.40 (cli) (built: Jan  9 2019 15:10:36)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

brucegust@BRUCEGUST7EFC MINGW64 /c/wamp64/www/new_nomas (bruce)
$ php artisan laravel

Parse error: syntax error, unexpected '?' in C:\wamp64\www\new_nomas\vendor\laravel\framework
\src\Illuminate\Foundation\helpers.php on line 500

Open in new window


I'm running PHP 7 on my box. The Laravel project I'm working on is also coming from a PHP 7 dynamic, so I don't know where the PHP 5.6.4 is coming from, but from what I've been able to determine, the error that I'm getting is because of PHP mismatch.

How do I fix it?
0
Hi everybody.
I'm learning Laravel and I've got an issue with the Auth code. The issue is that Laravel seems to pretend that to register a new user all registration form fields be filled, even the not required ones.

This is my RegisterController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{
  /*
  |--------------------------------------------------------------------------
  | Register Controller
  |--------------------------------------------------------------------------
  |
  | This controller handles the registration of new users as well as their
  | validation and creation. By default this controller uses a trait to
  | provide this functionality without requiring any additional code.
  |
  */

  use RegistersUsers;

  /**
   * Where to redirect users after registration.
   *
   * @var string
   */
  protected $redirectTo = RouteServiceProvider::HOME;

  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct()
  {
    $this->middleware('guest');
  }

  /**
   * Get a validator for an incoming registration request.
   *
   * @param  array  $data
   * @return 

Open in new window

0
Head out to http://new.brucegust.com and take a look at the index page. At the bottom you'll see a carousel of videos and testimonials.

I'm running the same code on my local box, but I'm getting an error that reads:

Undefined variable: videos (View: C:\wamp64\www\new_nomas\resources\views\welcome.blade.php)

Here's my route:

Route::get('/', 'PublicController@index')->name('index');

Here's my Controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Page;
use App\Video;
use App\Professional;
use App\Testimonial;

class PublicController extends Controller
{
    public function index() {
		$videos = Video::all();
		$testimonials = Testimonial::all();
		$data =  [
			'videos' => $videos,
			'testimonials' => $testimonials
		];
        return view('welcome', $data);
    }

Open in new window


And here's my welcome.blade.php page:

@extends('layouts.master')
@section('content')   
   <!-- Section: intro -->
    <section id="intro" class="intro">
        <div class="intro-content">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6">
                        <div class="wow fadeInDown" data-wow-offset="0" data-wow-delay="0.1s">
                            <h2 class="h-ultra">NOMAS<sup>&reg;</sup> International</h2>
                        </div>
                        <div class="wow fadeInUp" data-wow-offset="0" data-wow-delay="0.1s">
                            <h4 

Open in new window

0
Hi Experts

Could you give your opinion and hints about this modular approach by using Laravel?

Accordingly with the schema:
img001

The purpose is to appart the frontend from the server's code.

This modularity gives the possibility of to use the modules when it needed on a project.

F.e. : a site uses Quiz  - so the class represented by Module_Quiz is declared as an object of class Quiz on the main project.

In a very similar way that actually "vendor" class is declared at a common Laravel project.

At the front end - that could be using any frontend framework or jQuery/ Ajax, Laravel Blade - the server's code will be call by API.

It's probably an approach you had been using or has planned to use.

Thanks in advannce.
0
Head out to http://new.brucegust.com

You'll see a Laravel page I'm working on. You'll notice the page doesn't scroll.

You can make the page smaller and see the content as it exists towards the bottom (a couple of carousels etc.), but unless you make the page smaller, you can't scroll.

Why?
0
I've got a page with a list of testimonials and at one point on the site, I have this:

<a href="testimonials#{{$test->id}}">read more...</a>

The idea being that when the user clicks on the link, they're taken to the http://nomas.site/testimonials#2 and advanced to the testimonial with the id of 2.

I've got that particular testimonial listed with a <a name="2"></a> like you would expect but it doesn't seem to work.

Any ideas?
0
I'm using this to limit the number of characters displayed on a testimonial page:

{{ \Illuminate\Support\Str::limit($test->body, 100, '...') }}

I'm running Laravel 6 and it works just fine, except...

I really appreciate the content represented in NOMAS International. It's both helpful and interestin...

How can I do a "str_limit" without truncating the words?
0
Hi Experts

Could you point what parts of Laravel material (official or paralel) I must prefer to better improve my Eloquent knowledge - mainly fluid methods, if possible with some exercises?

Thanks in advance
0
Hi Experts

Could you point how to obtain the member "valor" and "period_id" from the json above?


{
	"tipoevento_id": 1,
	"user_id": 1,
	"created_at": "2020-03-02 13:08:01",
	"updated_at": "2020-03-02 13:08:01",
	"valor_atual": {
		"id": 1,
		"distribuidor_id": 9,
		"periodo_id": 1,
		"valor": "1000",
		"created_at": "2020-02-20 09:28:47",
		"updated_at": "2020-03-02 13:08:01",
		"mes": 1,
		"ano": 2020
	},
	"valor_anterior": {
		"id": 1,
		"distribuidor_id": 9,
		"periodo_id": 1,
		"valor": "300.0000",
		"created_at": "2020-02-20 09:28:47",
		"updated_at": "2020-02-20 09:28:47",
		"mes": 1,
		"ano": 2020
	},
	"id": 14
}

Open in new window



Thanks in advance!
0
Hi Experts

Could you point what must to be adjusted at this Laravel Eloquent query to consider a 2nd table join?                               
                              
                              
 $meta = Distribuidormeta
	::where('distribuidor_id', \DB::raw($distribuidor_id))
	->where('periodo_id', \DB::raw($mes))
	//->where('ano', \DB::raw($ano))
	->first();
	

Open in new window



The columns mes/ ano now belongs to the table periodos (it previously belonged to the table Distribuidormeta)


img001

Thanks in advance
0
Hi Experts

Could you point  how to handle Undefined Offset Error in Laravel?

This code:

        $registros = array();

        for($indexDistribuidor = 0; $indexDistribuidor<count($metas); $indexDistribuidor += 12){
            $item = array();
            array_push($item, $metas[$indexDistribuidor]->razaosocial);
            array_push($item, $metas[$indexDistribuidor]->cnpj);
            for($indexMes = 0; $indexMes < 12; $indexMes++){
                array_push($item, $metas[$indexDistribuidor + $indexMes]->meta);
            }

            array_push($item, $metas[$indexDistribuidor]->distribuidor_id);
            array_push($item, $ano);

            array_push($registros, $item);
        }

        return $registros;
		

Open in new window


During the foreach the array of objects is correctly been mounted.

But at certain point this offset error is produced:

 img004
Any workaround?

Thanks in advance.
0
Hi Experts

Could you point how to adjust this Laravel Eloquent query to remove the  ` at `2019`?

Accordingly with:
 $metas = XXXXXXX
            ::rightjoin(\DB::raw('(
                SELECT
                    distribuidores.id as distribuidor_id
                    ,distribuidores.cnpj
                    ,distribuidores.razaosocial
                    ,meses.mes
                    ,meses.nomeMes
                    ,meses.abreviatura
                    ,periodos.id as periodo_id
                    ,periodos.mes as periodo_mes
                    ,periodos.ano
                FROM distribuidores, meses, periodos
            ) as temp'), function($join) use($ano){
                $join->on('distribuidormetas.distribuidor_id', 'temp.distribuidor_id')
                     ->on('distribuidormetas.periodo_id', 'temp.periodo_id')
                     ->on('temp.mes', 'temp.periodo_mes')
                     ->on('temp.ano', (int)$ano);
            })
            ->where(function($query) use($distribuidor_id){
                if(!empty($distribuidor_id)){
                    $query->where('temp.distribuidor_id', \DB::raw($distribuidor_id));
                }
            })
            ->orderBy('temp.razaosocial', 'asc')
            ->orderBy('temp.mes', 'asc')
            ->select([
                'temp.distribuidor_id',
                'temp.cnpj',
                'temp.razaosocial',
                'temp.mes',
                'temp.nomeMes',
                

Open in new window

0
Hi Experts,

I'm having trouble creating a multi-dimension array to update a pivot table in Laravel with its corresponding attributes.

What I'm looking to do is have users select multiple entries from a list and once they submit their selections, I would like to add the "assigned_date" attributes to each selection when saving these records to the pivot table.


My Class Method:
public function assignUserAsset()
    {

        //Assume we can find this
        $user = User::find(1);
        $assignDate = date('Y-m-d');
        $attrib = ['assigned_date' => $assignDate];
        $assetArray = [1,2];

        //Attach current date to each selection
        $arr = [];
        foreach ($assetArray as $key) {
            $arr[] = [$key=>$attrib];
        }

        //Create entry in pivot table
        $user->assets()->attach($arr);


    }

Open in new window



dd($arr)
array:2 [▼
  0 => array:1 [▼
    1 => array:1 [▼
      "assigned_date" => "2020-02-27"
    ]
  ]
  1 => array:1 [▼
    2 => array:1 [▼
      "assigned_date" => "2020-02-27"
    ]
  ]
]

Open in new window



Error
arrayerror.PNG

I'm trying to follow this documentation here.

Specifically under section Many to Many Relationships - Attaching / Detaching

Documentation Sample

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([
    1 => ['expires' => $expires],
    2 => ['expires' => $expires],
]);

Open in new window



Can you please help understand what I'm doing wrong?

Thanks,
Ricky
0
Hi Experts,

I'm having trouble creating a mulitselect  Laravel form to show multiple columns. This is my current setup:

Controller:
public function edit($id)
    {
        //

        $user = User::findOrFail($id);
        $assets = Asset::all()->pluck('id', 'asset_name')->toArray();

        return view($_ENV['VIEW_FOLDER_VERSION'] . '/views/users/edit', compact('user', 'assets'));
    }

Open in new window



Blade:
<div class="form-group">
        {{Form::label('assets', 'Assets')}}
        {{Form::select('assets[]', $assets ,null,array('multiple'=>'multiple','name'=>'assets[]','class'=>'form-control'))}}
      </div>

Open in new window


MySQL Table
mysql.PNG

This is what I see:
multiselect.PNG

Can you please help point me in the right direction?

Thanks,
Ricky
0
Here's my code:

public function store(VideoRequest $request)
    {
        //
		$validated = $request->validated();
		$movie = new Video;
		
		if($request->hasFile('thumbnail')) {
			$file = $request->file('thumbnail');
			$thumbnail = $file->getClientOriginalName();
			$movie->thumbnail=$thumbnail;
			$file->move('assets/img', $thumbnail);
		}
			
		$movie->title=$validated['title'];
		$movie->description=$validated['description'];
		$movie->filename=$validated['filename'];
		$success='Video was successfully created!';
		
		if($movie->save()) {
			return View::make('/admin/displayVideo')
			->with('film', $movie)
			->with('newVideo', 'Here\'s the video you just created!');
		}
    }

Open in new window


It works!

All of the text, filenames etc are uploaded to the database and the thumbnail is accurately loaded into the appropriate directory..

But...

I get this error:

SplFileInfo::getSize(): stat failed for C:\wamp64\tmp\phpA213.tmp
(1/1) RuntimeException
SplFileInfo::getSize(): stat failed for C:\wamp64\tmp\phpA213.tmp

in RequestContext.php line 52
at SplFileInfo->getSize()
in RequestContext.php line 52
at RequestContext->Facade\FlareClient\Context\{closure}(object(UploadedFile))
at array_map(object(Closure), array('thumbnail' => object(UploadedFile)))
in RequestContext.php line 41
at RequestContext->mapFiles(array('thumbnail' => object(UploadedFile)))
in RequestContext.php line 36
at RequestContext->getFiles()
in RequestContext.php line 95
at 

Open in new window

0
Hi Experts,

The Problem
I'm trying to create a custom Laravel/Collective 6 form component as per instruction here.

I installed the Laravel/Collective package as per the previous link instruction using:
$ composer require laravelcollective/html

Open in new window


I have no problems with using the form as it seems to work just fine. I've only encountered errors when trying to register a macro or component to App\Providers\AppServicePrivider.php boot function with:
Form::component('bsText', 'components.form.text', ['name', 'value', 'attributes']);

Open in new window


This is what I see:
laravelcollective error
When trying to load the custom component I get the following error:
 Laravelcollective class error

What I've Tested
When checking previous laravelcollective version, namely, v5.6 and prior, I see the following instructions:
Laravel form v5.6 installation instruction
I've tried adding those entries to their respective locations in providers and aliases but it did not seem to help.


I'm not sure what I'm missing, Can you please help point me in the right direction?

Many thanks,
Ricky
0
Here's my code:

@foreach($videos as $video)
								<tr>
									<td><a data-toggle="modal" href="#video_player-{{ $video->id }}">{{ $video->title }}</a></td>
									<td style="text-align:center;"><a href="{{ url('/admin/show/video/' .$video->id) }}">edit</a> | <a data-toggle="modal" href="#deletePostModal-{{ $video->id }}">delete</a></td>
								</tr>
							@endforeach			

Open in new window


Bottom line: When the user clicks on the title of the video they get a popup that allows them to view the actual file.

I want to incorporate another feature, however, in that when the user hovers over the video title, they get a tooltip that lets them see the thumbnail associated with that file.

I can see how it's done, at least as far as being able to view some simple text like this:

https://www.w3schools.com/bootstrap/bootstrap_tooltip.asp

But how do I get two different functionalities to exist side by side with one being activated with a mouseover, the other with a click - both of which, apparently require the "data-toggle" dynamic?

Thanks!
1
I'm working in Laravel 6. I've got a list of videos and I've been able to structure things in a way where when the user clicks on the video's title, a pop up surfaces where you can hit play and video the video.

Perfect.

The problem is that when you close the modal, the video is still playing...

I need to incorporate a function that extends the "close" dynamic to include something that gets the video to stop playing.

One approach that I found seems to replace the video source with a ''. Seems reasonable, but I can't get it to work.

Here's a screenshot of the of the modal...

screenshot of modal
Here's the code I attempted to implement:

@foreach($videos as $video)
	<div class="modal fade" id="video_player-{{ $video->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" 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>
			<h5 class="modal-title" id="myModalLabel">{{ $video->title }}</h4>
		  </div>
		  <div class="modal-body" style="text-align:center;">
			<video width="320" height="240" controls id="video-frame-{{$video->id}}">
				<source src="{{ asset("assets/videos/{$video->filename}") }}" type="video/mp4">
				Your browser does not support the video tag.
			</video><br><br>
			<div style="text-align:left;">{{ $video->description }}</div>
		  </div>

Open in new window

0
Hi Experts


Could you point a Laravel library to send an email after an action?

After an user sends an image to be shown at a vitrine it must to be approved/ reproved by the admin and then an email must to be automatically sent to the user relating the result.

Thanks in advance
0
After successfully uploading an image using a form, I want to reference the uploaded image using the URL of the site combined with the file name.

I can do it by using this:

<img src="http://nomas.site/assets/img/{{ $film->thumbnail }}">

Obviously, while it's a short term fix, I want to use the asset helper, but I'm stuck in that when I try this:

<img src="{{ asset('assets/img/{{ $film->thumbnail }}') }}"

I'm coming up short.

What am I missing?
0
Hi Experts


Could you point what must to be adjusted at this view's code to avoid the form beeing submited if the modal's textbox is empty?

Accordingly with:


<?

<div class='row'>
    <br/>
    <div class="well well-lg text-center">
        <h1>Fotos</h1>
    </div>
</div>

<input type='hidden' id='pagina' value='1'/>

<div class="container">
    <div class="row">
    
          <!--div class="panel panel-primary"-->
          <div class="panel panel-default">
          
            <div class="panel-body">
                <div class=" col-md-12 col-sm-12"> 
                      <div class='row'>
                      
                         <div class="col-sm-12 col-md-6">
                          <div class="btn-group" role="group">
                            <button type="button" class="btn btn-primary" onclick="Xxxxx.vitrine.minhasfotos();">
                              <i class="fas fa-video" aria-hidden="true"></i> Minhas Fotos
                            </button>
                          </div>
                        </div>
                        
                         <div class="col-sm-12 col-md-3">
                          <div class="btn-group" role="group">
                            <button type="button" class="btn btn-primary" onclick="Xxxxx.vitrine.todasfotos();">
                              <i class="fas fa-video" aria-hidden="true"></i> Todas as Fotos
                            </button>
                          </div>
   

Open in new window

0
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

Laravel

195

Solutions

148

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
>