mleontenko

mleontenko

Member Since 2 Years Ago

Experience Points
7,810
Total
Experience

2,190 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
58
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 2
7,810 XP
Jul
30
1 week ago
Activity icon

Replied to Cloning Laravel Project (Ubuntu)

@bobbybouwmann my cloned application is not running at all because I cannot run

composer install

It returns the error described above.

If I create a new app, it works fine.

My first post is a bit messed up, and I cannot edit it because captcha solving is bugged :/

Activity icon

Replied to Cloning Laravel Project (Ubuntu)

@bobbybouwmann I already enabled it in php.ini.

But I don't thing it is the main problem here. It's just a warning.

See the part below the warnings, it tries to install all the dependencies and then returns:

"Your requirements could not be resolved to an installable set of packages."

And lists some problems.

Could it be that my new laptop has a newer version of php or laravel than the project?

Activity icon

Started a new Conversation Cloning Laravel Project (Ubuntu)

I have cloned a laravel project from my github on my new computer (Ubuntu 20.04). When I run composer install, I get the following message:

PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_pgsql' (tried: /usr/lib/php/20190902/pdo_pgsql (/usr/lib/php/20190902/pdo_pgsql: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/pdo_pgsql.so (/usr/lib/php/20190902/pdo_pgsql.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'pgsql' (tried: /usr/lib/php/20190902/pgsql (/usr/lib/php/20190902/pgsql: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/pgsql.so (/usr/lib/php/20190902/pgsql.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  Module 'intl' already loaded in Unknown on line 0
PHP Warning:  Module 'mbstring' already loaded in Unknown on line 0
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for phpoffice/phpspreadsheet 1.14.0 -> satisfiable by phpoffice/phpspreadsheet[1.14.0].
    - phpoffice/phpspreadsheet 1.14.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
  Problem 2
    - phpoffice/phpspreadsheet 1.14.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - maatwebsite/excel 3.1.19 requires phpoffice/phpspreadsheet ^1.10 -> satisfiable by phpoffice/phpspreadsheet[1.14.0].
    - Installation request for maatwebsite/excel 3.1.19 -> satisfiable by maatwebsite/excel[3.1.19].

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.4/cli/php.ini
    - /etc/php/7.4/cli/conf.d/10-opcache.ini
    - /etc/php/7.4/cli/conf.d/10-pdo.ini
    - /etc/php/7.4/cli/conf.d/15-xml.ini
    - /etc/php/7.4/cli/conf.d/20-calendar.ini
    - /etc/php/7.4/cli/conf.d/20-ctype.ini
    - /etc/php/7.4/cli/conf.d/20-dom.ini
    - /etc/php/7.4/cli/conf.d/20-exif.ini
    - /etc/php/7.4/cli/conf.d/20-ffi.ini
    - /etc/php/7.4/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.4/cli/conf.d/20-ftp.ini
    - /etc/php/7.4/cli/conf.d/20-gettext.ini
    - /etc/php/7.4/cli/conf.d/20-iconv.ini
    - /etc/php/7.4/cli/conf.d/20-intl.ini
    - /etc/php/7.4/cli/conf.d/20-json.ini
    - /etc/php/7.4/cli/conf.d/20-mbstring.ini
    - /etc/php/7.4/cli/conf.d/20-phar.ini
    - /etc/php/7.4/cli/conf.d/20-posix.ini
    - /etc/php/7.4/cli/conf.d/20-readline.ini
    - /etc/php/7.4/cli/conf.d/20-shmop.ini
    - /etc/php/7.4/cli/conf.d/20-simplexml.ini
    - /etc/php/7.4/cli/conf.d/20-sockets.ini
    - /etc/php/7.4/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.4/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.4/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.4/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.4/cli/conf.d/20-xmlreader.ini
    - /etc/php/7.4/cli/conf.d/20-xmlwriter.ini
    - /etc/php/7.4/cli/conf.d/20-xsl.ini
    - /etc/php/7.4/cli/conf.d/20-zip.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

If I create a new laravel project on my machine and run it like this:

laravel new blog
cd blog
php artisan serve

What is the problem? Why can't I run the old app?

Then everything works fine.

Jul
22
2 weeks ago
Activity icon

Started a new Conversation Installing Laravel On Ubuntu

I'm trying to install laravel on Ubuntu 20.04 like this:

composer global require laravel/installer

It returns the following messages:

PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_pgsql' (tried: /usr/lib/php/20190902/pdo_pgsql (/usr/lib/php/20190902/pdo_pgsql: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/pdo_pgsql.so (/usr/lib/php/20190902/pdo_pgsql.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'pgsql' (tried: /usr/lib/php/20190902/pgsql (/usr/lib/php/20190902/pgsql: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/pgsql.so (/usr/lib/php/20190902/pgsql.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  Module 'intl' already loaded in Unknown on line 0
PHP Warning:  Module 'mbstring' already loaded in Unknown on line 0
Changed current directory to /home/marin/.config/composer
Using version ^3.2 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
11 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

Now, when I try to run:

laravel new blog

It returns the following message:

laravel: command not found

What is wrong here?

Jun
30
1 month ago
Activity icon

Replied to Filter By Attribute From Pivot Table

@frankielee I'm using this operators() method in view while rendering, so I cannot use controller here.

I have three possible roles, so I'm planning to add three separate methods for fetching all the users with the role. The one above is just for example.

Activity icon

Started a new Conversation Filter By Attribute From Pivot Table

I have the following method in my model that retrieves all the related users and their roles:

public function operators()
{
        return $this->belongsToMany('App\User', 'obrasciOperateriUloge', 'id_obrasca', 'id_operatera')->withPivot('role');        
}

The results look like this:

[
   {
      "id":8,
      "name":"jjozic",
      "firstname":"Jozo",
      "lastname":"Jozi\u0107",
      "email":"[email protected]",
      "email_verified_at":null,
      "admin":false,
      "active":true,
      "phone":"555",
      "created_at":"2020-03-09 11:26:16",
      "updated_at":"2020-03-09 11:26:16",
      "edited_by":null,
      "edited_at":null,
      "pivot":{
         "id_obrasca":43,
         "id_operatera":8,
         "role":"Author"
      }
   },
   ...
]

I want to add an aditional filter in operators() method that returns only the users with role "Author". How can I do this?

Jun
15
1 month ago
Activity icon

Started a new Conversation Set Attribute Based On Id

I have an object model that has an attribute named "code" that is generated based on object id. The problem is I cannot access object id in my controller before it is stored because it is auto increment. Is there a simple way to add "code" attribute when storing object?

The "code" attribute would contain id with leading zeros like this:

str_pad($object_id, 6, '0', STR_PAD_LEFT);
May
25
2 months ago
Activity icon

Replied to Display Time With Timezone

@snapey thanks, was not aware that I can set timezone in config/app.php. That should work for me in this case.

Activity icon

Started a new Conversation Display Time With Timezone

I have a Post model that contains creation date in timestamp without timezone:

$table->dateTime('creation_date');

Example: 2020-05-22 09:54:34

It seems to store dateTime in GMT time zone andshows it like that in my view:

{{ date('d.m.Y. H:i', strtotime($post->creation_date)) }}

I want to convert it to local timezone in view. How can I do that?

May
20
2 months ago
Activity icon

Replied to Query With Attributes From Related Model

@michaloravec Thanks, that will work!

I used Post - Category analogy only for example, my app has entirely different classes that would be harder to explain. It's true this logic would be wrong in Posts and Categories case...

Activity icon

Started a new Conversation Query With Attributes From Related Model

I have a Post model that can have multiple categories:

The relationship looks like this:

public function categories()
    {
        return $this->hasMany('App\PostsCategories', 'post_id', 'id');
    }

PostsCategories table contains IDs of posts and their categories.

I'm trying to query posts by multiple criteria (post name, category, etc.) like this:

public function search(Request $request)
{   
    $post_name= $request->post_name;
    $category_id= $request->category_id; // value is integer 1- 20

    $posts= Post::query()
            ->where('post_name', 'LIKE', "%{$post_name}%")
            // and where category equals $category_id
            ->paginate(50);
}

I'm having trouble with figuring out how to add category to my query. How can I include attributes form related models in my query?

Apr
28
3 months ago
Activity icon

Started a new Conversation Retain Value Of Radio Button, But Set Default Value

I'm using old() to retain radio button selection after form validation error in Laravel, but I also want to make option "Unknown" selected by default.

The form element looks like this:

<label for="description">Product Available</label><br/>
<label class="radio-inline"><input type="radio" name="available" id="available" value="yes" {{ (old('available') == 'yes') ? 'checked' : ''}}>Yes</label>
<label class="radio-inline"><input type="radio" name="available" id="available" value="no" {{ (old('available') == 'no') ? 'checked' : ''}}> No</label>
<label class="radio-inline"><input type="radio" name="available" id="available" value="unknown" {{ (old('available') == 'unknown') ? 'checked' : ''}}> Unknown</label>

This works fine, but I need the "Unknown" option to be set by default when opening form without overriding "old()" data.

How can I do this?

Apr
22
3 months ago
Activity icon

Replied to Get Related Records In Query

@snapey I don't think the result is wrong, related record is not the same record, it is record with id: 2 ("related_id" attribute). The result just includes all results from table that stores relationships ("related_records" table). If record 1 was also related to record 3, the result would look like this:

[
   {
      "id":1,
      "name":"record 1",
      "related_records":[
         {
            "id":1,
            "record_id":1,
            "related_id":2
         },
   	 {
            "id":1,
            "record_id":1,
            "related_id":3
         }
      ]
   }
]

I don't know if this is good approach, but it definitely provides a way to get IDs of related records. I'm trying to find a way to get those related records together with the one I searched for (not just their IDs, but models).

Activity icon

Replied to Get Related Records In Query

@snapey so I don't need to use hasMany relation?

How would this join look like in laravel query builder?

I know a way to do using subqueries and CTEs, but I have a feeleing there is a more elagant way to solve it.

Activity icon

Replied to Get Related Records In Query

@michaloravec from what I understand, it returns related records in the form of pivot table like this:

[
   {
      "id":1,
      "name":"record 1",
      "related_records":[
         {
            "id":1,
            "record_id":1,
            "related_id":2
         }
      ]
   }
]

Let's assume record 1 is related to record 2.

When I search for record 1, what I need returned is:

[
   {
      "id":1,
      "name":"record 1"
   },
  {
      "id":2,
      "name":"record 2"
   }
   ...
]

Because in related records there is:

id | record_id  | related_id
___________________________
1 |      1      |       2

Sorry if I'm unclear, it is a bit hard for me to explain this.

Activity icon

Started a new Conversation Get Related Records In Query

I have the following table for records:

record:
	id
	name

and another table that stores related records (user defines related records when creating a new one):

related_records:
	id
	record_id
	related_id

One record can have multiple related records.

In Record model I have defined a relation:

public function related()
    {
        return $this->hasMany('App\Related', 'record_id', 'id');
    }

Now, when I search records by name like this:

Record::query()->where('name', 'LIKE', "%{$searchTerm}%")->get();

I also want to include all related records from results. How can I do this?

Apr
21
3 months ago
Activity icon

Replied to Storing Array Of Integers To Database Field

@bugsysha they represent just some list values. The list would be predefined (without adding values) with only id and value columns, so I woldn't go that far with models and relationships if it's possible to query contents of json field.

Activity icon

Replied to Storing Array Of Integers To Database Field

@bugsysha thanks. And what about querying (E. g. all records that contain option 1.)? Would that work here and how?

Activity icon

Started a new Conversation Storing Array Of Integers To Database Field

I have the following table:

record:
	id: 1
	version: "1.0"
	options: [1, 3, 5]

The controller should look like this:

public function store(Request $request)
{
	$record = new Record;
	$record->version = "1.0";
	$record->options = $request->options;

	return redirect()->to('/records')->with('success', 'Record saved.');
}

Options field in database should contain an array of integers, but I'm unsure which data type to use in migration. Any suggestions?

Also, will I be able to query this field? E. g. all records that contain option 1.

Apr
20
3 months ago
Activity icon

Started a new Conversation Checkboxes From XML Template

I have the following XML template (I plan to keep it as a separate xml file):

<doc>
	<version>1.0</version>
	<option>
		<id>1</id>
		<name>Option 1</name>
	</option>
	<option>
		<id>2</id>
		<name>Option 2</name>
	</option>
	<option>
		<id>3</id>
		<name>Option 3</name>
	</option>
	<option>
		<id>4</id>
		<name>Option 4</name>
	</option>
	<option>
		<id>5</id>
		<name>Option 5</name>
	</option>
</doc>

XML template is not mandatory, another format like JSON can be used. I just need to keep my options structured somewhere. Feel free to suggest something else.

I want to generate form with checkboxes for each of these options like this:

The checkboxes would store selections to array options[]

After submitting the form, I want to store this array into a field named "options", table named "record"

Example:

record:
	id: 1
	version: "1.0"
	options: [1, 2, 3]

I have a few questions regarding this:

  1. What data type should field "options" be?
  2. Will I be able to query this table for options and how? E. g. I want all records containing option 1
  3. What is the simplest way to generate form with checkboxes from template? Also consider that I want to repopulate selections with values from array in case of editing.
Apr
17
3 months ago
Activity icon

Started a new Conversation Return Many To Many Relationship Data To View

I have the following tables:

users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer

And many to many relationship:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
    }
}

I want to display a user with all his roles in view, so Controller looks like this:

public function show($id)
    {        
        $user = User::find($id);

        $roles= $user->roles();

        $user->roles= $roles;

        return view('users.show')->with('user', $user);
    }

The problem is there is in my view, if I print {{$user }}}, roles looks like this:

"roles":{
      "withTimestamps":false
   }

How can I make $user->roles contain data for each role in my view?

Apr
16
3 months ago
Activity icon

Replied to LaravelCollective Form Model Binding

@snapey you mean form model binding or Laravel collective ? :D

Activity icon

Started a new Conversation LaravelCollective Form Model Binding

I have a form for editing posts that looks like this:

{!! Form::model($post, ['action' => ['[email protected]', $post->id], 'method' => 'POST']) !!}       
        <div class="form-group">
            {{Form::label('title', 'Title:')}}
            {{Form::text('title', '', ['id' => 'title', 'class' => 'form-control'])}}
        </div> 
	<div class="form-group">
            {{Form::label('content', 'Contenti:')}}
            {{Form::textarea('content', '', ['id' => 'content', 'class' => 'form-control'])}}
        </div>      
        {{Form::hidden('_method', 'PUT')}}   
        {{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
    {!! Form::close() !!}

The $post model looks like this:

{
   "id":1,
   "title":"Post one",
   "content":"Lorem ipsum dolor sit amet...",
}

Is there a way to automatically fill form with content of $post model (which is passed when opening form) without me explicitly setting values to form like this:

{{Form::text('title', $post->title, ['id' => 'title', 'class' => 'form-control'])}}

Form::text requires second parameter to be some value, so I cannot leave it empty....

Activity icon

Replied to Map Query HasMany To Array

@snapey if I try $post->comments()->modelKeys()

It returns Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::modelKeys() error

EDIT:

It works if I remove parentheses like this: $post->comments->modelKeys()

Thanks!

Activity icon

Replied to Map Query HasMany To Array

@tykus Thanks, that will work.

But I will still need some way to convert related models to array of IDs in some other situations. For example, when I want to repopulate select input that supports multiple selections. Any ideas?

Activity icon

Started a new Conversation Map Query HasMany To Array

I have two tables, "posts" and "comments".

One post can have multiple comments:

In Post model:

public function comments()
    {
        return $this->hasMany('App\Comment', 'post_id', 'id');
    }

When I delete Post, I also want to delete related comments, so delete method in controller looks like this:

$post= Post::find($id);

$comments = $post->comments;

The $comments looks like this:

[
   {
      "id":8,
      "comment_id":1,
      "post_id":7,
      "created_at":"2020-04-16 08:53:07",
      "updated_at":"2020-04-16 08:53:07"
   },
   {
      "id":9,
      "comment_id":19,
      "post_id":7,
      "created_at":"2020-04-16 08:53:07",
      "updated_at":"2020-04-16 08:53:07"
   }
]

What I want is to map comment id's to array named $comment_ids, so I can delete them like this before the post is deleted:

DB::table('comments')->whereIn('id', $comment_ids)->delete();

How can I do this?

Apr
15
3 months ago
Activity icon

Replied to Changing Field Type With Migration

@kalemdzievski that's the source of problem.

I had to add double quotes to table name like this:

Schema::table('"obrasciProcjeneVrste"', function ($table) {
    $table->string('sifra', 256)->change();
});

It works after that. Thanks!

Activity icon

Replied to Changing Field Type With Migration

@kalemdzievski if I delete this migration file and run php artisan migrate it returns "Nothing to migrate". All the other migrations were executed successfully earlier. So I think this file is the issue.

Also, the error says specifically:

Undefined table: 7 ERROR:  relation "obrasciprocjenevrste" does not exist

Why is my table name in this error converted to lowercase (it is actually camel cased both in code and database)? Could that be problem?

This is the full migration file code:

<?php

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

class ChangeSifra extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('obrasciProcjeneVrste', function ($table) {
            $table->string('sifra', 256)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Apr
14
3 months ago
Activity icon

Replied to Populate Select Element With Data From Multiple Columns

@snapey I tried that, and it returns this error:

Illuminate\Database\QueryException
SQLSTATE[42703]: Undefined column: 7 ERROR: column "fullname" does not exist LINE 1: select "fullname", "id" from "users" ^ (SQL: select "fullname", "id" from "users")

Could somethong be wrong with my query?

$users= DB::table('users')->pluck('fullname', 'id');

Both "firstname" and "lastname" attributes exist, so I guess accessor is good...

Activity icon

Started a new Conversation Populate Select Element With Data From Multiple Columns

I have the following select element in my form:

<div class="form-group">
    {{ Form::label('users', 'Users:') }}
    {{ Form::select('users[]', $users, null, ['id' => 'users', 'class' => 'form-control', 'multiple' => 'multiple']) }}
</div>

The data is passed to form view via controler like this:

$users = DB::table('users')->pluck('lastname', 'id');

This works fine, but in my users table, I also have "firstname" that I want to concatenate with lastname and fill the form. How can I do this?

Activity icon

Started a new Conversation Changing Field Type With Migration

I have a table with an integer field type that I want to change to varchar (postgres database)

I installed:

composer require doctrine/dbal

and created a new migration with:

public function up()
    {
        Schema::table('obrasciProcjeneVrste', function ($table) {
            $table->string('sifra', 256)->change();
        });
    }

When I run php artisan migrate

I get the following error:

Doctrine\DBAL\Exception\TableNotFoundException  : An exception occurred while executing 'SELECT obj_description('obrasciProcjeneVrste'::regclass) AS table_comment;':

SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "obrasciprocjenevrste" does not exist
LINE 1: SELECT obj_description('obrasciProcjeneVrste'::regclass) AS ...
                               ^

  at C:\xampp\htdocs\crveni-popis\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\AbstractPostgreSQLDriver.php:63
    59|             case '42703':
    60|                 return new Exception\InvalidFieldNameException($message, $exception);
    61| 
    62|             case '42P01':
  > 63|                 return new Exception\TableNotFoundException($message, $exception);
    64| 
    65|             case '42P07':
    66|                 return new Exception\TableExistsException($message, $exception);
    67| 

  Exception trace:

  1   Doctrine\DBAL\Driver\AbstractPostgreSQLDriver::convertException("An exception occurred while executing 'SELECT obj_description('obrasciProcjeneVrste'::regclass) AS table_comment;':

SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "obrasciprocjenevrste" does not exist
LINE 1: SELECT obj_description('obrasciProcjeneVrste'::regclass) AS ...
                               ^", Object(Doctrine\DBAL\Driver\PDOException))
      C:\xampp\htdocs\crveni-popis\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:166

  2   Doctrine\DBAL\DBALException::wrapException(Object(Doctrine\DBAL\Driver\PDOPgSql\Driver), Object(Doctrine\DBAL\Driver\PDOException), "An exception occurred while executing 'SELECT obj_description('obrasciProcjeneVrste'::regclass) AS table_comment;':

SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "obrasciprocjenevrste" does not exist
LINE 1: SELECT obj_description('obrasciProcjeneVrste'::regclass) AS ...
                               ^")
      C:\xampp\htdocs\crveni-popis\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:146

What is the problem here? Table name in migration file exists in database ("obrasciProcjeneVrste") and field name is correct ("sifra").

Apr
06
4 months ago
Activity icon

Started a new Conversation Redirect With Message If Foreign Key Violated On Delete

If I use delete on a database record that has foreign key associated to it, I get the following error:

SQLSTATE[23503]: Foreign key violation: 7 ERROR: update or delete on table "users" violates foreign key constraint...

The code in controller looks like this:

public function destroy($id)
{
        $user = User::find($id);
        $user->delete();

        return redirect('/admin')->with('success', 'User deleted.');
    }

I'm fine with the above mentioned constraint, but I want to return to a view with an error like this if constraint is violated:

return redirect('/admin')->with('error', 'Cannot delete user with associated records.');

How can I catch the error to return this message?

Mar
19
4 months ago
Activity icon

Started a new Conversation Logging ID While Storing New Record To Database

I have created logs table and Log model. When I insert something to database (e.g. a new post), I want to log some basic info.

For example: User creates a post. In Posts Controller:

// Create Post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->user_id = auth()->user()->id;
$post->cover_image = $fileNameToStore;
$post->save();

// Log the creation
$log = new Log;
$log->user_id= Auth::id();
$log->post_ id= ???;
$log->date = time();
$log->save();

return redirect('/posts')->with('success', 'Post Created');

The problem is that I don't have Post ID at this stage, so I can't log it. How can I solve this?

Mar
10
4 months ago
Activity icon

Started a new Conversation Laravel Collective Radio Button Breaks After Specifying Extra HTML Attributes

I have the following radio buttons in my form:

<div class="form-check">                
    {{Form::radio('active', 'true', true, ['class' => 'form-check-input'])}}
    {{Form::label('active', 'Yes', ['class' => 'form-check-label'])}}
    {{Form::radio('active', 'false', ['class' => 'form-check-input'])}}
    {{Form::label('active', 'No', ['class' => 'form-check-label'])}}
</div>               
               	

I explicitly set the first option (Yes) to be checked, but in my application, the second one is checked (No). If I remove ['class' => 'form-check-input'] part, it checks the right one. What is wrong here?

I'm using laravel collective for the forms.

Activity icon

Replied to Login Fails After Changing User Model

@sti3bas That works. Thanks!

Mar
09
5 months ago
Activity icon

Replied to Login Fails After Changing User Model

@sti3bas I'm using both. Default one is for anonymous user to register, and the one from tutorial is for application administrator to create users through forms.

But, both controllers use the same model (User). Following the tutorial broke the default register (it double hashes now) because I added hashing function to User model.

Activity icon

Replied to Login Fails After Changing User Model

@sti3bas because I created User CRUD like in this tutorial: https://vegibit.com/how-to-create-user-registration-in-laravel/

it specifies that I need to add that method to User class to ensure hashed passwords (otherwise they would not be hashed).

So, passwords created through Register are double hashed, and the ones created through CRUD are fine... Is there a way to remove hashing from RegisterController because I added it in model? Could it solve this problem?

Activity icon

Replied to Login Fails After Changing User Model

@jlrdw Could the problem be this function in my User class:

public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

I added that because I created user CRUD like here: https://vegibit.com/how-to-create-user-registration-in-laravel/

You think that broke "out of the box" auth system?

Activity icon

Replied to Login Fails After Changing User Model

@sinnbeck No, I did not rollback migrations. Also, If I create new user through database, it works fine, I can login/logout without any problems. Only users created through register form have this problem.

Passwords are hashed with bcrypt

if I create user manually through database, I use: https://bcrypt-generator.com/

Activity icon

Replied to Login Fails After Changing User Model

Clearing browser cache does not work here. Also, I'm working on the application locally and I did not set up email for resetting password, so I can't do that...

Activity icon

Started a new Conversation Login Fails After Changing User Model

I have expanded default User model in Laravel with additional fields like firstname, lastname, admin (boolean field) etc.

Registration and works fine, and it logs me in for the first time, but if I log out, I can't login anymore. I get the "These credentials do not match our records." error when I try to login. What could be wrong?

My user model is modified and looks like this:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'firstname', 'lastname', 'email', 'password', 'admin', 'active', 'phone'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Add a mutator to ensure hashed passwords
     */
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Migration model looks like this:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('firstname')->nullable();
            $table->string('lastname')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('admin')->default(false);
            $table->boolean('active')->default(true);
            $table->string('phone')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->string('edited_by')->nullable();
            $table->timestamp('edited_at')->nullable();
        });
    }

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

Mar
03
5 months ago
Activity icon

Replied to User Administration

Nova looks good, but since this is for learning purposes, I will need a free alternative...

Activity icon

Started a new Conversation User Administration

I have a default User class from Laravel built in system and I added some custom fields in database For example, I added boolean field "verified". I want to create an admin panel where system administrator can manually create users, change their data and passwords.

What is the best way to do this? I was planning to use Laravel backpack. Are there any better alternatives?

Feb
19
5 months ago
Activity icon

Replied to One To Many Relation In Forms (without JavaScript)

Ok, I understand that this is impractical to implement with pure PHP because it would refresh the page on button click, but is there any library/package that helps me do something like this in laravel?

What I'm trying to do is avoid writing custom JS code that handles button click events and DOM manipulation because this way of handling many-to-many relationships seems like something that is used commonly in web forms. The values are sent to the controller as an array and are easy to handle after that.

Activity icon

Started a new Conversation One To Many Relation In Forms (without JavaScript)

I have a form for adding address to a user. One user can have anything from zero to dozens of addresses (one to many relationship in database).

Is there a simple way to create a form in Laravel that allows the user to add or delete address fileds without writing custom JavaScript code that handles add/delete buttons?

It should look something like this:

View post on imgur.com