codemode

Experience

10,940

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 84 Lessons Completed
  • 0 Favorites

9th April, 2018

codemode left a reply on Path To File Stored In Storage • 2 months ago

Ah, all i needed was : php artisan storage:link Thanks @Snapey and @jlrdw

8th April, 2018

codemode left a reply on Path To File Stored In Storage • 2 months ago

Hi @Snapey , adding 'public' does save the file under the public folder.

But, '/storage/'.$path; would be www.domain.com/storage/profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpg , isn't it? That does not work :(

codemode left a reply on Path To File Stored In Storage • 2 months ago

Hi @jlrdw , do you mean store the file under resources/assets instead of the storage/ folder?

7th April, 2018

codemode started a new conversation Path To File Stored In Storage • 2 months ago

Sorry for asking a question that has been asked several times before, but i could not solve my problem yet.

I'm trying to simply save a picture into my local storage, and then to access it's URL.

Here is the controller :

´´´ public function uploadProfilePic(Request $request) { $user_id = Auth::user()->id;

  $path = $request->file('profilePic')->store('profilePics/'.$user_id);

}

´´´ The $path above returns a value like : ´profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpeg´

And the file is stored as : storage/app/profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpeg

1.) Is the above, the right place to store public images, or should they be placed inside "storage/app/public"

2.) What is the file URL? I tried : www.domain.com/storage/app/profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpg , www.domain.com/storage/profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpg , www.domain.com/profilePics/1/xGZJVdD3cSoyawPe8ZkZmSNyuKoE8KsTG1UZHoEW.jpg

But none of them seem to work. Filesystems.php configuration is kept default.

Thanks.

2nd March, 2018

codemode left a reply on User - Post - Likes To A Post By User • 3 months ago

AH got it, in my PostLike model, i was not returning the relationship... all i had to do was to return it.. It works now!!

Also, i just tried with Post::with(['user', 'post_like.user']) ... and that works too! :)

Thanks!

codemode left a reply on User - Post - Likes To A Post By User • 3 months ago

Hi @skliche ,

You're right, the view had to iterate through all the likes. This is what i've done now :

@if(count($all_posts))
                    @foreach($all_posts as $post)
                    <div>
                        <ul>{{ $post->body }} - by {{ $post->user->name }} | Likes = {{ count($post->post_like) }}
                         <ul> | Liked by = @foreach($post->post_like as $likes)
                                        <li>{{ $likes->user->name }}</li>
                                        @endforeach
                          </ul>
                        </ul>
                    </div>
                    @endforeach
                    
                    @endif 

In my controller if i just do this :

$all_posts = Post::all();
return view('wall', compact('all_posts'));

Then i see an error : App\PostLike::user must return a relationship instance.

What do you think? Thanks!

1st March, 2018

codemode left a reply on User - Post - Likes To A Post By User • 3 months ago

@skliche Thank you for pointing this out.

the dump($post->post_like); dumps an array which does contain the user_id.

I'm not sure how do i get the user's names from here :(

If i do $all_posts = Post::with('post_like')->with('user')->get(); - Then on doing a dd(), i see the the user's information.. Could you tell me how can i access it?

(And just to confirm, doing the Post::with('post_like')->with('user')->get(); instead of Post::with('user')->get(); will give me the users who have LIKED the post, right?)

Thanks!

codemode started a new conversation User - Post - Likes To A Post By User • 3 months ago

Hello, I have 3 models - User, Post and PostLike . So, a User can create many posts, and each post can be liked by users. I', trying to get a user to like a particular post, and the be able to display all the users who have liked a particular post.

User Model : ´´´ public function posts() { return $this->hasMany(Post::class); }

public function post_like()
{
    return $this->hasMany(PostLike::class);
}

´´´

Post Model : ´´´ public function user() { return $this->belongsTo(User::class); }

public function post_like()
{
    return $this->hasMany(PostLike::class);
}

´´´

PostLike Model : ´´´ public function post() { $this->belongsTo(Post::class); }

public function user()
{
    $this->belongsTo(User::class);
}

´´´

The Post Controller, where i display a list of all my posts : ´´´ public function index() { $all_posts = Post::all();

    return view('wall', compact('all_posts'));
}

´´´

Now, i try to display the posts, it's likes, and the users who have liked it : ´´´ @if(count($all_posts)) @foreach($all_posts as $post)

    {{ $post->body }} - by {{ $post->user->name }} | Likes = {{ count($post->post_like) }} | Liked by = {{ $post->post_like->user->name}} // This is throwing errors {{ csrf_field() }} <input type="hidden" name="likeThePost" value={{ $post->id or '' }} /> Like
@endforeach @endif ´´´

Please check my comment "This is throwing errors" above. I'd appreciate if someone can point me to the right direction.

Thanks.

11th February, 2018

codemode left a reply on Need Help With SQL Query - Stuck Since Days • 4 months ago

Thanks!

codemode left a reply on Need Help With SQL Query - Stuck Since Days • 4 months ago

Hello @burlresearch , the query ran fine on my local machine, but does not run on the server.

This is the error i see :

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'DBNAME.m.s_value' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Any ideas? Thanks.

6th February, 2018

codemode left a reply on Need Help With SQL Query - Stuck Since Days • 4 months ago

HOLY cow dude, that works like a charm!! Thank you @burlresearch , you saved my life! :) :)

3rd February, 2018

codemode left a reply on Need Help With SQL Query - Stuck Since Days • 4 months ago

Hi @burlresearch , yes you're right. However, the the field item_meta.s_value will have the same value for each user.

So, in simple words, each time an ITEM is created, for a particular user, the item_meta.s_value will be same each time.

Thank you..

2nd February, 2018

codemode started a new conversation Need Help With SQL Query • 4 months ago

Hello,

My question is more about a SQL query, rather than Laravel.

There is a table called ´item_meta´ which has a foreign key ´fk_i_item_id´ and a field ´s_value´.

And a table called ´t_user´ which has the primary key ´pk_i_id´ , and a field ´s_phone_mobile´

And a table called ´t_item´ which has the primary key ´pk_i_id´, a foreign key ´fk_i_user_id´

So, ´t_user´ has many ´t_item´ and an ´t_item´ has one ´item_meta´ .

I want to transfer the data from the field ´s_value´ of the table ´item_meta´ into the field ´s_phone_mobile´ of the table ´t_user´

The horribly wrong SQL query is as follows :

´´´ insert into t_user(pk_i_id, s_phone_mobile) select fk_i_item_id, s_value from t_item_meta where fk_i_item_id = some connection with the user table ´´´

I've been with this since days and days, i would be very content if someone could help me here.

Thanks.

28th January, 2018

codemode left a reply on Eloquent Relationship In Users & Friendships • 4 months ago

anyone?

27th January, 2018

codemode started a new conversation Eloquent Relationship In Users & Friendships • 4 months ago

Hello,

I'm having some trouble in the 'friend' relationship in a social network.

I have a Friendship model, which has a one-to-many relationship with User model. So, each user can have many friendships.

User model :

public function friendships()
    {
        return $this->hasMany(Friendship::class);
    }

Friendship model:

 public function user()
    {
        return $this->belongsTo(User::class);
    }

The friendship table has fields : id, user_id, requested_to, and status.

So, to display a user's friends, the status has to be accepted.

The controller logic to display my list of friends is this :

public function showFriends(Request $request)
    {
        //show friends whose status = accepted on friendships table
        
        //get current logged in user
        $user_id = Auth::user()->id;
        
        $my_friends = Friendship::where('requested_to', $user_id)->where('status', 'accepted')->with('user')->get();
        
        return view('friends.my-friends', compact('my_friends'));
    }

Though this works, but it shows the list of friends to ONLY the person who has RECEIVED a friend request... but does not show to the person who has SENT the friend request.

I think i'm not able to understand how the relationship has to be set between User and Friendship. Please help.. thanks.

codemode left a reply on Simple Delete Request Logic • 4 months ago

It works, thanks guys!

24th January, 2018

codemode started a new conversation Simple Delete Request Logic • 4 months ago

Hi,

I'm trying to create a delete request, but i'm missing something very basic.

Route : Route::post('/dashboard/delete', '[email protected]');

Controller :

public function deleteStack(Request $request)
    {
        $this->validate(request(), ['deleteButton' => 'required']);
        
        $sender = $request->deleteButton;
        
        $user_id = Auth::user()->id;
        
        DB::table('stacks')->where('user_id', $sender)->where('requested_to', $user_id)->delete();
         
        return redirect('/dashboard/index');
        
    }

View: <form method="POST" action="{{ url('/dashboard/delete') }}">

Thanks!

13th January, 2018

codemode left a reply on Laravel Custom Validation • 5 months ago

The documentation actually has the typo error. Thanks for pointing out @bobbybouwmann

codemode started a new conversation Laravel Custom Validation • 5 months ago

In my controller i'm doing some validation like :

 $this->validate(request(),  
            [ 'add_button' => 'required|integer|notIn:'.$requested_by ], 
            [ 'notIn' => 'This value has to be different' ]);

...this is in reference to the following format : $this->validate($request, $rules, $customMessages);

So, i'm using the "notIn" validator to check that the "add_button" value is not equal to "$requested_by"

Though the validation works, but the custom message is not not displayed. On the contrary, if i put a custom validation message for "required" or something like "max" - then the custom validation message is displayed just fine.

Where am i going wrong?

Thanks.

11th January, 2018

codemode started a new conversation Help With SQL Query • 5 months ago

Hello,

I have a fairly nasty SQL query, which i'm not able to execute. So, i need to extract 2 fields for selected dates... and then the same 2 fields for just the last 6 months. I decided not to use Eloquent for the sake of ease.

Given the circumstances, i need to fit all this into ONE sql query.

Following is what i have right now :

select customerAccount, 
        count(id) as countIdAll ,
        sum(amount) as sumAmtAll,
        count(case when (updated_at >= date_sub(now(), interval 1 month) ) then id else 0 end) as countId6,
        sum(case when (updated_at >= date_sub(now(), interval 6 month) ) then amount else 0 end) as sumAmt6,
        count(updated_at) as countUpdate, 
        updated_at from transactions 
        WHERE updated_at BETWEEN "'.$from.'" AND "'.$to.'"
        group by  customerAccount order by customerAccount

As you can see, the countIdAll returns the number of times the ID is present The sumAmtAll returns the sum of amount The countId6 "should" return the count of ID for the last 6 months only And the sumAmt6 "should" return the sum of amount for the last 6 months only.

The countId6 and sumAmt6 are returning the same values as countIdAll and sumAmtAll... which is not what i want.

Any help is appreciated, thanks.

10th January, 2018

codemode left a reply on How Is "class User Extends Authenticatable" Different From "class User Extends Model" • 5 months ago

@kreierson So, does the Authenticable class also inherits frunctions from Eloquent too?

codemode started a new conversation How Is "class User Extends Authenticatable" Different From "class User Extends Model" • 5 months ago

When we use Laravel's standard Auth feature to scaffold the login/registration, we see the User model created as "class User extends Authenticatable" , "class User extends Model".

How different are they from each other.. and can i use the current state of the User model which extends "Authenticable".. and relate it to another model say Posts like :

return $this->hasMany(Post::class); ?

Thanks.

5th January, 2018

codemode started a new conversation General Doubt On How Search Engines List Certain URLs • 5 months ago

Hello,

My question is less about laravel, but more about SEO.

Suppose that i have a very standard Post model, which contains title, description & slug (for the title) - related to a user.

The way i wanted to display the url for a post with the title "my first post" and id as 1 : www.website.com/1/my-first-post

The id above is what decides post to display, and the slug is just passed as data, which does not really control which post is displayed. For example : www.website.com/1/qwerty - will display the same post as above.

Now, how does search engines like google or bing decide what will be the URL listed by them? Does google recognize URLs by how many people have accessed a particular URL, or does it iterate through all the links that are present from the root of my domain... or does it recognizes URLs by some php/laravel way?

Many thanks.

10th December, 2017

codemode left a reply on Getting The Right Validation Error • 6 months ago

facepalm.. The field names where different.

codemode left a reply on Getting The Right Validation Error • 6 months ago

@Snapey , i get the same error this way too. (using L5.5)

codemode left a reply on Pulling In Old Data On Form Input After Validation Error • 6 months ago

Thanks again @Snapey , it works!

codemode started a new conversation Getting The Right Validation Error • 6 months ago

I have a controller, where i have done vlaidation like -

$this->validate(request(), [
            'title' => 'required|string|max:100',
            'description' => 'required|string|max:10000'
  ]); 

When i post the form with the title more than 100 characters (and description with valid no. of chars), i get the flash error as - ERROR : The title field is required. ERROR : The description field is required.

Should't it say something like "Error: The title has more than 100 characters" ?

I'm displaying the errors on my views like -

@if ($errors->any())
@foreach ($errors->all() as $error)
            <b>Error :</b> {{ $error }}
@endforeach 
@endif

How can i display the right error? Thanks!

codemode started a new conversation Pulling In Old Data On Form Input After Validation Error • 6 months ago

Hello,

Here - https://laravel.com/docs/5.5/requests#old-input , it says i can pull in the old inputted value like <input type="text" name="username" value="{{ old('username') }}">

..which works good for input type text, but does not work for textareas.

I do not get the data back when i do - <textarea class="form-control" name="post-description" value="{{ old('post-description') }}" placeholder="Description" rows="10" required></textarea>

Ideas?

Thanks!

8th December, 2017

codemode left a reply on General Doubts On Standard Login Blade Template Generated By Laravel • 6 months ago

I see..

So i think the following code will add the css class "has-error", in case of an error.

form-group{{ $errors->has('email') ? ' has-error' : '' }}

But then why do we have these two separate, since we are displaying just a common error? -

{{ $errors->first('password') }}

{{ $errors->first('email') }}

Thanks.

codemode started a new conversation General Doubts On Standard Login Blade Template Generated By Laravel • 6 months ago

Hello,

Following is the file generated by the make:auth artisan command.

<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

1.) What condition is form-group{{ $errors->has('email') ? ' has-error' : '' }} - this is the first line of the code above.

2.) How does this -

@if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
@endif

..differ to this -

@if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
 @endif

The way it seems, is that irrespective of weather email, or password is wrong, i get a message "wrong credentials" - be it email or password wrong.

What errors would the 2nd part of point 2 display?

Thanks!

17th November, 2017

codemode left a reply on How Many Javascript Frameworks Should I Learn That Is "enough"? • 7 months ago

Sure, you'll be capable enough if you're good with HTML, CSS, Laravel & VueJs. You can build any web application using those technologies. Ofcourse, there'll be always different opinions on it, but in general, yes that is quite sufficient.

As for JS frameworks, there will never be an "enough". JS frameworks are evolving rapidly, and every few months there'll be new stuff coming.

If you're focusing on Laravel, i think VueJs is a very convenient choice (although any other will work too).

Just keep the pace and keep learning, you'll get there :) Good luck!

9th November, 2017

codemode left a reply on Passing Dynamic Title Tags • 7 months ago

Thanks @Stratos , is there anyway we can confirm this?

8th November, 2017

codemode left a reply on Passing Dynamic Title Tags • 7 months ago

...just found that removing the {{ }} will remove the XSS protection that blade provides - https://laravel.com/docs/5.5/blade#displaying-data

Any thoughts?

codemode left a reply on Passing Dynamic Title Tags • 7 months ago

Ah, i missed the brackets.

So, this is the right format! - @section('title', $post->title ) , and it works! Thanks!

codemode left a reply on Passing Dynamic Title Tags • 7 months ago

@topvillas sorry for the confusion, on doing a simple @section('title', {{ $post->title }}) , i get a syntax error.

I.e. on using quotes, i see the php syntax on my title, and without quotes, i see an error.

codemode started a new conversation Passing Dynamic Title Tags • 7 months ago

Hello,

In the laravel docs, there is an example to pass different values to the tag as seen here - https://laravel.com/docs/5.5/blade#extending-a-layout

However, if i do something like @section('title', '{{ $post->title }}') on a page extending a master page, i get a syntax error.

I understand i can do a <title>{{ $post->title }}</title> , but that doesn't seem right if i'm defining the title as <title>@yield('title')</title> in my master page.

Is there a way i can pass dynamic values using @section, @yield and {{$value}} ?

Thanks!

7th November, 2017

codemode left a reply on Aligning Main Section And Sidebar To One Row • 7 months ago

Thanks Cronix. I wanted to keep all posts separate in each panel.

Putting the loop right after the col-md-8 did it, like this -

        <div class="col-md-8">
            @foreach ($posts as $post)
            <div class="panel panel-default">

codemode started a new conversation Aligning Main Section And Sidebar To One Row • 7 months ago

Hi,

Sorry for posting here, but my question is more about bootstrap and blade. In my blade.php file, i need to display all individual posts in a col-md-8 , and a sidebar with col-md-4 - so both of these sections could be aligned at the top side to side.

But, the current setup i have makes the sidebar appear at the bottom instead of the top. I can't really place the sidebar between the blade's foreach loop, since that will replicate the sidebar.

I think i'm placing the col-md's wrong. Below is my code -

@section('all-posts')
<div class="container">
    <div class="row">
        @foreach ($posts as $post)
        <div class="col-md-8">
            <div class="panel panel-default">
                <a href="/posts/{{ $post->id }}/{{ $post->slug }}">
                    <div class="panel-heading">{{ $post->title }} </div>
                </a>
                <p>{{ $post->description }}</p>
                        <p>by 
                            @if(!empty($post->user->name)) 
                                {{ $post->user->name }} 
                            @else
                                 Anonymous
                            @endif
                        </p> 
            </div>
        </div>
        @endforeach
        
         <div class="col-md-4">
                <div class="panel panel-default">
                    <div class="panel-heading">Sidebar</div>
                    @include('layouts/sidebars/latest-comments')
                </div>
        </div>
        </div> 
    </div> 

Thanks.

27th October, 2017

codemode left a reply on How To Handle Url Changes Upon Editing • 7 months ago

Hi @Talinon I need the slug in the id

codemode left a reply on How To Handle Url Changes Upon Editing • 7 months ago

Thanks @Daveismyname , but hardcoded redirects would not be the best idea here. It's better to dynamically set the redirect when a post is edited.

codemode started a new conversation How To Handle Url Changes Upon Editing • 7 months ago

Hi,

In my little project, i am displaying the url of a post with the id and the slugged title, like - website.com/5/the-fifth-title

The slug is generated by the str_slug() method (https://laravel.com/docs/5.5/helpers#method-str-slug)

Now, when a user edits the post, and the title changes to something like "The modified fifth title" - the title will change to website.com/5/the-modified-fifth-title

In such a case, though my website links will be aware of this change, but not the search engines.

What would be the best approach to automatically redirect the old url to the new url?

Many thanks!

20th October, 2017

codemode left a reply on Allowing Only Certain Values To Be Accepted On A Dropdown • 8 months ago

:O Dude, that god-damn worked!

codemode started a new conversation Allowing Only Certain Values To Be Accepted On A Dropdown • 8 months ago

I have a simple dropdown to choose the gender on the registration form like -

<select name="gender" class="col-md-4 control-label">
        <option value="male">Male</option>
         <option value="female">Female</option>
 </select>

But, when i change the values on chrome's inspection tools, i can easily modify the values and can store on the DB.

How can i restrict the values only to male and female.

Is there a way i can add a condition to my Controller's validation?

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'gender' => 'required|string' //and add a condition for just "male" and "female"
        ]);
    }

Thanks

codemode started a new conversation Adding Fields To The Standard Register Controller • 8 months ago

Hi,

In a new laravel project i've done "make:auth" to make the authentication. I am trying to include two new fields "gender and dob".

Gender is required, and dob is optional.

RegisterController -

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'gender' => 'required|string'
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'gender' => $data['gender'],
     
        ]);
    }

Filled in fillables in the User model -

 protected $fillable = [
        'name', 'email', 'password', 'gender', 'dob'
    ];

And here is the migration file -

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('gender');
            $table->string('dob')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

Added this to the register.blade.php -

<div class="form-group{{ $errors->has('gender') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Gender</label>

                            <div class="col-md-6">
                                <select name="gender" class="col-md-4 control-label">
                                    <option value="male">Male</option>
                                    <option value="female">Female</option>
                                </select>
                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('gender') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

Upon doing the above, when i try to register a new user, i get - ErrorException (E_NOTICE) Undefined index: dob

Help please, thanks!

29th September, 2017

codemode left a reply on Route Duplicated • 8 months ago

Hi @Snapey thanks for your input. Could you explain the reason please? Cheers.

codemode left a reply on Route Duplicated • 8 months ago

Aha, got it. I'm using a cloud dev environment, and my vhosts root has more than one project, so i guess laravel was confused to find what the actual path is.

26th September, 2017

codemode left a reply on Route Duplicated • 8 months ago

I could run it with action="{{ $post->id }}/comments" ..but i don't get it. Where is the "posts" getting appended from?

codemode started a new conversation Route Duplicated • 8 months ago

I'm following this tut - https://laracasts.com/series/laravel-from-scratch-2017/episodes/16

..where a comment form has to be added on views/posts/show.blade.php like :

` {{ csrf_field() }} Add Comment

`

My CommentsController :

` class CommentsController extends Controller { public function store(Post $post) { Comment::create([

        'body' => request('body'),
        'post_id' => $post->id
        
    ]);

    return back();
}

} `

And the route file : Route::post('posts/{post}/comments', '[email protected]');

On submitting the form, i see the URL goes to 'localhost/posts/posts/1/comments' , instead of 'localhost/posts/1/comments'

Where am i going wrong? Thanks!

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.