princeoo7

princeoo7

Member Since 1 Year Ago

Experience Points 3,120
Experience Level 1

1,880 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 10
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

04 Jul
2 weeks ago
03 Jul
2 weeks ago

princeoo7 left a reply on How Html Developer Can Work With Live Site?

with live site builder like what we have in wordpress, its only going to make the CSS and HTML rome around, but when their will be logic, you will be stuck. as the dev to look at vuejs tutorials so that in a week or so he / she can start on small to medium scale projects. it's not a big deal now a days if developer is flexible to have a positive learning attitude towards learning new things / technology.

princeoo7 started a new conversation Paginate BelongsToMany Relationship Records If More Than Set Limit

How do we paginate records for belongsToMany relationship ?

i was watching laracasts lesson: Laravel From Scratch: Part 31 - Sorting Posts By Tags url : https://youtu.be/Lq9rOAYW-S0

but there is not part talking about pagination for relational records : (

my code is as below:

 public function index(Category $category)
    {
        $posts = $category->posts;
        dd($posts);
        return view('pages.frontend.categories.index', compact('posts'));
    }

i get around 50 records for the current category i am checking post for. I want to have a limit of 20 record per page.

if i do :

$posts = $category->posts->paginate(20);

i get error:

 BadMethodCallException

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

princeoo7 left a reply on Get Distinct Eloquent Relation Data Count And Records In Laravel

right now i was so confused that i thought that range(1,27) will give me a single number and not an array and so i got confused here.

i got things working but let me break it down so that it will be on record for me to refer in future and also you might be able to tell me if i understood the code and it's flow correct.

1st : gives me an number array from 1 to 27.

$categoryIds = range(1, 27);

2nd : shuffle the newly generated 1 to 27 array.

shuffle($categoryIds);

3rd : we slice the array from index 0 to the random number generate and so we get a unique length for the array for each post category.

$categoryIds = array_slice($categoryIds, rand(0, count($categoryIds) - 1));

4th: we insert / attach those ids to the post with pivot table. though i really didn't knew that an array also works as same as an object or id of the relative data. Some thing new learned today.

$post->categories()->attach($categoryIds );

let me know if i am right or not. marking your answer as correct answer :)

princeoo7 left a reply on Get Distinct Eloquent Relation Data Count And Records In Laravel

Schema::create('category_post', function (Blueprint $table) {
        $table->integer('category_id');
        $table->integer('post_id');
        $table->primary('category_id', 'post_id');
    });

    Schema::create('post_tag', function (Blueprint $table) {
        $table->integer('post_id');
        $table->integer('tag_id');
        $table->primary('post_id', 'tag_id');
    });

Is this right ?

princeoo7 left a reply on Get Distinct Eloquent Relation Data Count And Records In Laravel

currently i am using faker to seed the db and this is what i am doing in the seeder for post:

foreach (range(1, 27) as $key => $value) {
            $post->categories()->attach(mt_rand(1, 27));
            $post->tags()->attach(mt_rand(1, 27));
        }

princeoo7 started a new conversation Get Distinct Eloquent Relation Data Count And Records In Laravel

i want to get distinct records inside a category.

my code in [email protected]

$posts = Category::where(['title' => request('category'),  'status' => 1])
        ->with('posts')
        ->paginate(env('RECORD_LIMIT'));

and in my category model :

public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public static function archives()
    {
            return static::selectRaw('title')
            ->withCount('posts')
            ->get()
            ->toArray();
    }

neither the count of archive is right nor the records i am getting as their are many duplicate records. what is wrong and how to solve this issue ?

princeoo7 left a reply on Query Filter Some Time Returns Null In Laravel

@EDOC - it's the same query just as i tried to solve it with the provided solution, i ended up with another error for the same problem. but now it's solved and i have marked the question answered.

princeoo7 left a reply on Query Filter Some Time Returns Null In Laravel

the final solution was the below code:

public function scopeFilter($query)
    {
        if ($month = request('month')) {
                $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if ($year = request('year')) {
                $query->whereYear('created_at', $year);
        }
    }

i was parsing the $year also with carbon and that was the issue. we don't need to return any thing as it's part of the query i suppose.

princeoo7 left a reply on Query Filter Some Time Returns Null In Laravel

@RAS1212 - this works but one tiny problem now.

if i have post/may/2018 as the url i expect post from may 2018, but now i am getting all record which have month may and the year condition is skipped i suppose :/

princeoo7 left a reply on Query Filter Some Time Returns Null In Laravel

@RAS1212 - I was referencing to url : https://youtu.be/n3mKQ0o1Xr4

and in it there was no return so i never set return :(

princeoo7 left a reply on Query Filter Some Time Returns Null In Laravel

@RAS1212 - Well that was embarrassing :/ such silly mistake from my side :(

one more thing if possible related to the same topic.

if i use:

->filter(request(['month', 'year']))

instead of

 ->filter(['month' => $request->month, 'year' => $request->year])

I end up with

Undefined index: month

reference video link :

princeoo7 started a new conversation Query Filter Some Time Returns Null In Laravel

I was going through the laravel from scratch episode for archives.

the problem i am facing is that some times for some archive dates, no data is fetch even if the record exist in db.

the query fired is as below as per the dd(DB::getQueryLog());

array:1 [▼

0 => array:3 [ "query" => "select count(*) as aggregate from `pos where ((`stat = ?) and month((`created_) = ? and year((`created_) = ?" "bindings" => array:3 [ 0 => 1 1 => "12" 2 => 2019 ] "time" => 0.84 ] ]

fetching post code :

$posts = Post::latest()->with('author')
            ->where(['status' => 1])
            ->filter(['month' => $request->month, 'year' => $request->year])
            ->paginate(env('RECORD_LIMIT'));

filter code from scope in Post model:

public function scopeFilter($query, $filter)
    {
        if ($month = $filter['month']) {
                $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if ($year = $filter['year']) {
                $query->whereYear('created_at', Carbon::parse($year)->year);
         }
    }

where am i going wrong ?

below is the query fired for fetching three records:

array:3 [ 0 => array:3 [ "query" => "select count(*) as aggregate from om `p where (e (`st = ?) and month(th(`create) = ? and year(ar(`create) = ?" "bindings" => array:3 [ 0 => 1 1 => "04" 2 => 2019 ] "time" => 0.68 ] 1 => array:3 [ "query" => "select * from * fro where (where = ?) and month(month(`cr) = ? and year(d year(`cr) = ? order by der by `cr desc limit 20 offset 0" "bindings" => array:3 [ 0 => 1 1 => "04" 2 => 2019 ] "time" => 0.75 ] 2 => array:3 [ "query" => "select * from ect * where ers`.re in (13, 29, 64)" "bindings" => [] "time" => 0.66 ] ]

25 Jun
3 weeks ago

princeoo7 started a new conversation Need Help With Setting Up Laravel Web Routes As Frontend And Vue-router As Backend Spa With Jwt-auth.

In last few days i have been trying to make a laravel website with laravel web routes as for frontend (seo benifits) and as for backend vuejs spa with jwt-auth.

i was following below medium tutorial :

https://medium.com/@ripoche.b/create-a-spa-with-role-based-authentication-with-laravel-and-vue-js-ac4b260b882f

the original source code works well but if i do composer update and npm update, mostly due to latest vuejs version, i start getting cros error for the api. if i install the laravel-cros package, the error goes but then i am stuck with error: unauthorized after login and can't push the login vue in vue-router.

now that's just the first problem.

in web.php it have a code:

// Route to handle page reload in Vue except for api routes
    Route::get('/{any?}', function (){
        return view('welcome');
})->where('any', '^(?!api\/)[\/\w\.-]*');

this will redirect any request to welcome page.

i only want that to happend when some one wish to login and go to dashboard. reset of the time normal laravel routes is to be used as i can do SSR for seo.

i tried adding below code:

Route::get('/', function (){
        return view('index');
});




// Route to handle page reload in Vue except for api routes
    Route::get('/dashboard/{any?}', function (){
        return view('welcome');
})->where('any', '^(?!api\/)[\/\w\.-]*');

it works but then when it comes to vue spa, the url gets replaced by:

http://localhost:3000/login

instead of :

http://localhost:3000/backend/login

and on successful login, the vue-router don't push the new vue as the user part is unauthorized for some reason which i am not able to understand or find i must say :(

please help me out if someone knows anything about this situation. thank you for going through my post. have a nice day ahead :)

23 Jun
4 weeks ago

princeoo7 started a new conversation Laravel Spa

I followed the below tutorial and completed it. but when it came to login part for testing. i am able to get success status as mentioned in the tutorial but can't pust dashboard for the that user ( admin / user ). because i am getting error : unauthorized in network tab.

now i tried downloading this version from his git repo and that works. but as soon as i run npm update for as i have some packages which requires latest vue. i get the CROS error and on solving them the project runs but then, after successful login success status, on redirect ( vue-router push ) i get stucked on the login page and also i get the error : error : unauthorized in network tab. now what code is wrong or where things are not working is a real issue for me to understand :(

link: https://medium.com/@ripoche.b/create-a-spa-with-role-based-authentication-with-laravel-and-vue-js-ac4b260b882f

06 Jun
1 month ago

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@SNAPEY - Oh man, you are a life saver <3 Thank you so much :D

05 Jun
1 month ago

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@SERGIU17 -

$records = $tag::with([
        'articles' => function ($query) {
            $query->paginate(20);
        }
    ]);

code above gave me, i think builder query :

Builder {#372 ▼
#query: Builder {#366 ▶}
#model: Tag {#373 ▶}
#eagerLoad: array:1 [▶]
#localMacros: []
#onDelete: null
#passthru: array:13 [▶]
#scopes: []
#removedScopes: []
}

attaching ->get(); at the end gave me :

$records = $tag::with([
        'articles' => function ($query) {
            $query->paginate(20);
        }
    ])->get();

Result:

Collection {#397 ▼
#items: array:25 [▼
 0 => Tag {#403 ▶}
    1 => Tag {#404 ▶}
    2 => Tag {#405 ▶}
    3 => Tag {#406 ▶}
    4 => Tag {#407 ▶}
    5 => Tag {#408 ▶}
    6 => Tag {#409 ▶}
    7 => Tag {#410 ▶}
    8 => Tag {#411 ▶}
    9 => Tag {#412 ▶}
    10 => Tag {#413 ▶}
    11 => Tag {#414 ▶}
    12 => Tag {#415 ▶}
    13 => Tag {#416 ▶}
    14 => Tag {#417 ▶}
    15 => Tag {#418 ▶}
    16 => Tag {#419 ▶}
    17 => Tag {#420 ▶}
    18 => Tag {#421 ▶}
    19 => Tag {#422 ▶}
    20 => Tag {#423 ▶}
    21 => Tag {#424 ▶}
    22 => Tag {#425 ▶}
    23 => Tag {#426 ▶}
    24 => Tag {#427 ▶}
]
}

all tags dispite of passing a tag name as a param. to the url : http://localhost:3000/blog/tag/quia

even if i try doing

public function index(Tag $tag)
{
    $records = $tag::with([
        'articles' => function ($query) {
            $query->paginate(20);
        }
    ])->get();

    return dd($records->articles);

}

i get error:

Property [articles] does not exist on this collection instance.

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

@JOHNBRAUN - yes i did the same but and now only thing i am stuck is adding pagination to them:

$records = $tag::with('articles')->paginate(20);
    // or
    $records = $tag->load('articles')->paginate(20);

return dd($records->articles);

i get the error :

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$articles

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@SERGIU17 - I get the result either with load() or with() but anything about having pagination ?

i still get:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$articles

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@SERGIU17 updated my answer previously as i solved the prior issue and stuck in new one :(

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@SERGIU17 - Oh i see, i thought that the route can have any name for the param. my bad.

one slight request i have, i am trying to get the reverse relation for articles.

but in tags i can get the articles data and not articles relations.

like in articles i get $articles > tag > author > meta.

here i get $tags > article.

how to do some thing like this ?

#reference question url : https://laracasts.com/discuss/channels/laravel/eager-loading-2-out-of-3-returned-as-null

i am stuck here from yesterday :(

princeoo7 left a reply on Route Model Implicit Binding Not Working For Me.

@sergiu17 updated the question / query ...

princeoo7 started a new conversation Route Model Implicit Binding Not Working For Me.

Source: https://laravel.com/docs/5.8/routing#route-model-binding

I was trying laravel from scratch ep 30 and 31 and found jeffery doing implicit binding of route but when i tried i get null result. why so ?

Tag model :

class Tag extends Model
{
        public function articles()
        {
         return $this->belongsToMany(Article::class);
     }

        public function getRouteKeyName()
        {
            return 'name';
        }
}   

<./code>

Tag Controller

use App\Tag;
use Illuminate\Http\Request;

class TagsController extends Controller
{
    public function index(Tag $tag)
        {
            return $tag;
        }

}

whats wrong in my code ?

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

@JOHNBRAUN - i solved that but now i am not able to get the reverse properly.

means i have the following code in the Tag model,

class Tag extends Model
{
    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

    public function getRouteKeyName()
 {
        return 'name';
    
}

and in Tag controller :

public function index(Tag $tag)
    {
     return $tag;
    }

in jeffery video 30 for laravel from scratch it works but for me it's not working.

if i do :

Tag::with('articles')->get();

it works but only article is retrived and not tag > article > author + tags + meta where as i was expecting tag > article > author + tags + meta.

this is find of confusing right now for me as i am still learning this stuff.

04 Jun
1 month ago

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

how does @jeffery gets the following code get working ?

TagModel

class Tag extends Model
{
        public function articles()
        {
            return $this->belongsToMany(Article::class);
        }

        public function getRouteKeyName()
        {
            return 'name';
        }
}

and TagController

public function index(Tag $tag)
    {
        return $tag;
 }

web.php

Route::get('/blog/tag/{name}', '[email protected]')->name('blogs.showbyTag');

referencing to laracasts video for Laravel From Scratch: Part 31 - Sorting Posts By Tags

https://www.youtube.com/watch?v=Lq9rOAYW-S0

i get nothing. blank and jeffery gets an output :/

@

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

@JOHNBRAUN - typo in the sense in the belongsToMany I forgot Many ;)

but author is same and started working itself. weird :/

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

Ok just got the dd() removed and saw that the data was passed. my back i shall have checked it prior commenting it.

princeoo7 left a reply on Eager Loading, 2 Out Of 3 Returned As Null

@JOHNBRAUN - i did made the change as it was a typo on my part but i am just getting the below output

"author" => User {#441 ▶}
      "meta" => MetaData {#469 ▶}
      "tags" => Collection {#471 ▼
        #items: array:1 [▼
          0 => Tag {#508 …26}
        ]
      }

now what does 0 => Tag {#508 …26} represent ? any clue ?

03 Jun
1 month ago

princeoo7 started a new conversation Eager Loading, 2 Out Of 3 Returned As Null

i have the following code:

article controller

$records = Article::where(['status' => 1])->with(['author', 'meta', 'tags'])->orderBy('id', 'DESC')->paginate(20);

article model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model { public $timestamps = true;

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

public function meta()
{
    return $this->HasOne(MetaData::class, 'article_id');
}

public function tags()
{
    return $this->belongsTo(Tag::class);
}

}

29 May
1 month ago

princeoo7 left a reply on Any Tutorial Where It's Show How To Make A Website In Laravel With Vuejs Spa As Backend In It ?

@NOMGUY - no i want vue spa for backend ( dashboard ) but still thanks for a suggestion. really appreciate it :)

princeoo7 started a new conversation Any Tutorial Where It's Show How To Make A Website In Laravel With Vuejs Spa As Backend In It ?

I am trying to build a website with laravel and was to use vuejs spa as a backend. don't want to have a separate vuejs app. in short normal routes of laravel in frontend, but vue routers in backend for dashboard. any help with it ?

Route::get('/dashboard/{any}', function () {
        return view('pages.backend.index');
})->middleware('auth')->name('any', '*');

i was trying something like this in my web.php file. it works for

http://localhost:3000/dashboard/blog/

but fails to render

http://localhost:3000/dashboard/blog/create

16 May
2 months ago

princeoo7 left a reply on Update Laravel Installer Version

@TALENTEDAAMER - no it's ^2.1 as of now.

06 May
2 months ago

princeoo7 left a reply on Event Listener With Popup Notification?

i am also looking for something similar :)

02 May
2 months ago

princeoo7 left a reply on [89] Invalid Or Expired Token With Thujohn/twitter In Laravel

Issue Solved. by removing extra space at the end of all 4 keys.

then

php artisan config:cache

and last but not least

php artisan cache:clear

princeoo7 started a new conversation [89] Invalid Or Expired Token With Thujohn/twitter In Laravel

Hello Everyone !

I was trying to get feeds fro twitter based on tags with thujohn/twitter package.

every thing seems fine but i get the error as below:

[89] Invalid or expired token.

i have properly updated the .env files with credential like this: ( below are fake ofcourse )

.env

TWITTER_CONSUMER_KEY=adsfsdvveswdrversdfgvbxdrecvv
TWITTER_CONSUMER_SECRET=gt6XIt9m2pasdasdasdsfdgvdfJzA5gIvGn82LdPcG3yEEJ5Ix
TWITTER_ACCESS_TOKEN=G9GWnaverdsvxffcdvgzefvbgn hADWSCtlKDT2ZwNowUq
TWITTER_ACCESS_TOKEN_SECRET=Versfdxvsvdfvdscvxxvbszeddzvdssc

ttwitter.php

// You can find the keys here : https://apps.twitter.com/

return [
    'debug'               => function_exists('env') ? env('APP_DEBUG', false) : false,

    'API_URL'             => 'api.twitter.com',
    'UPLOAD_URL'          => 'upload.twitter.com',
    'API_VERSION'         => '1.1',
    'AUTHENTICATE_URL'    => 'https://api.twitter.com/oauth/authenticate',
    'AUTHORIZE_URL'       => 'https://api.twitter.com/oauth/authorize',
    'ACCESS_TOKEN_URL'    => 'https://api.twitter.com/oauth/access_token',
    'REQUEST_TOKEN_URL'   => 'https://api.twitter.com/oauth/request_token',
    'USE_SSL'             => true,

    'CONSUMER_KEY'        => function_exists('env') ? env('TWITTER_CONSUMER_KEY', '') : '',
    'CONSUMER_SECRET'     => function_exists('env') ? env('TWITTER_CONSUMER_SECRET', '') : '',
    'ACCESS_TOKEN'        => function_exists('env') ? env('TWITTER_ACCESS_TOKEN', '') : '',
    'ACCESS_TOKEN_SECRET' => function_exists('env') ? env('TWITTER_ACCESS_TOKEN_SECRET', '') : '',
];

and calling it like below in controller

use Twitter;

$records = Twitter::getUserTimeline(['screen_name' => 'Laravel', 'count' => 20, 'format' => 'json']);

What is going wrong and how should i solve this problem.

27 Mar
3 months ago

princeoo7 started a new conversation How To Integrate Prismjs In Laravel And Vue

I wish to know how to integrate prismjs in laravel and vuejs.

i did

npm install prismjs --save  

then will do

import Prism from 'prismjs';

after this what ?

official documentation say's

var Prism = require('prismjs');
var loadLanguages = require('prismjs/components/');
loadLanguages(['haml']);

// The code snippet you want to highlight, as a string
var code = "= ['hi', 'there', 'reader!'].join \" \"";

// Returns a highlighted HTML string
var html = Prism.highlight(code, Prism.languages.haml, 'haml');

but this is only for one language. what we want support for multiple languages ? like php, python, html5 or css and more ?

princeoo7 left a reply on How To Use Extend Vue In Blade File With Like We Do In Vue Components ?

@FTIERSCH - I may be using two or more methods and computed properties. normally we export default in vue component. but how to do this exact in blade file ? @prepend and @push works for the main app.js but export default is not working.

princeoo7 started a new conversation How To Use Extend Vue In Blade File With Like We Do In Vue Components ?

I want to know how to extend the vue default inside the blade file like we do in .vue file. The reason is that i don't want my main app.js file to have big file size. for example there are 5 vue component i want to use in a single blade file which i will be only using it in this single file / url, why should i load it on every other request ?

How to keep it short and simple.

example can be a blog index page where i have one component to render later blog with pagination, one component for feeds, one for news or recent search, one for most popular blogs, one for category, one for tags and one for search.

26 Mar
3 months ago

princeoo7 left a reply on Fetch All Posts Tags In Polymorphic Relation Statically

@PALAK - can you show the dd() output ? normally $tag->post->id should work in a loop.

princeoo7 left a reply on Are The Laracasts Php Tutorials Enough To Learn Php?

Jeffery's tutorial are great to start with. it's mainly common things user but go through documentation for more. no tutorial in the world will give you 100% knowledge as with every iteration something comes and till that time we are still working / learning the old stuff.

I started my PHP with is w3schools and then his tutorials from tutsplus. I will recommend him any time.

and if you are wondering who is Jeffery, he is the founder of this platform ;)

princeoo7 left a reply on How To Access Data In Nested / Multi Dimensional Array In Vue File ?

@ETTORE - the issue was solved as the error was in belongsTo and hasOne relation of article and user. thank you for your feed back :)

22 Mar
3 months ago

princeoo7 left a reply on Getting Null In Eloquent Relation Data After 3 Records !

@MARKYZZZ - this one worked and as i was now using paginate, blogs.data was to be accessed and not just blogs.

thank you for your help :)

princeoo7 left a reply on Getting Null In Eloquent Relation Data After 3 Records !

@MUNAZZIL -

LengthAwarePaginator {#268 ▼
#total: 50
#lastPage: 5
#items: Collection {#265 ▼
    #items: array:10 [▼
    0 => Article {#277 ▼
        #guarded: []
        #connection: "mysql"
        #table: "articles"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:13 [▶]
        #original: array:13 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: array:2 [▼
        "author" => User {#263 ▶}
        "moderator" => User {#269 ▶}
        ]
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
    }
    1 => Article {#278 ▶}
    2 => Article {#279 ▶}
    3 => Article {#280 ▶}
    4 => Article {#281 ▼
        #guarded: []
        #connection: "mysql"
        #table: "articles"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:13 [▶]
        #original: array:13 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: array:2 [▼
        "author" => null
        "moderator" => null
        ]
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
    }
    5 => Article {#282 ▶}
    6 => Article {#283 ▶}
    7 => Article {#284 ▶}
    8 => Article {#285 ▶}
    9 => Article {#286 ▶}
    ]
}
#perPage: 10
#currentPage: 1
#path: "//localhost:3000/blogs"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
#options: array:2 [▶]
}

please have a look at this.

princeoo7 started a new conversation Getting Null In Eloquent Relation Data After 3 Records !

For some reason, I am getting null as eloquent relation data.

below is the code i have written.

public function index()
{
    return response()->json(
        [
            'blogs' => Article::with(['author', 'moderator'])->paginate(10)
        ],
        200
    );
}

and my article model file is like this:

class Article extends Model
{
    protected $guarded = [];

    public function getTags()
    {
        return $this->hasMany(Tag::class);
    }

    public function getCategory()
    {
        return $this->hasOne(Category::class);
    }

    public function author()
    {
        return $this->hasOne(User::class, 'id');
    }

    public function moderator()
    {
        return $this->hasOne(User::class, 'id');
    }
}

princeoo7 started a new conversation How To Access Data In Nested / Multi Dimensional Array In Vue File ?

Hello Everyone.

As laravel for backend, i am able to fetch data from axios and the following structure is what i get.

{"blogs":[{"id":1,"title":"Commodi molestias nulla necessitatibus blanditiis harum non ratione. Fugiat tenetur natus enim qui consequatur sequi. Et voluptatem at quibusdam ullam.","slug":"Commodi-molestias-nulla-necessitatibus-blanditiis-harum-non-ratione.-Fugiat-tenetur-natus-enim-qui-consequatur-sequi.-Et-voluptatem-at-quibusdam-ullam.","banner":"public\/uploads\/ba\/\569387b8daf1969c5907618ad1aad455.jpg","description":"Quia delectus voluptate aut recusandae reiciendis facere.","category_id":7,"body":"7","views":1,"status":1,"author_id":1,"moderator_id":1,"created_at":"2019-03-22 07:11:35","updated_at":"2019-03-22 07:11:35","author":{"id":1,"name":"XYZ USER","email":"[email protected]","email_verified_at":null,"created_at":"2019-03-06 14:14:59","updated_at":"2019-03-06 14:14:59"},"moderator":{"id":1,"name":"XYZ USER","email":"[email protected]","email_verified_at":null,"created_at":"2019-03-06 14:14:59","updated_at":"2019-03-06 14:14:59"}}]}

now in vue file i am trying to access it like this

<tr v-for="article in blogs" :key="article.id">
    <td>{{article.id}}</td>
    <td>{{article.title}}</td>
    <td>{{article.slug}}</td>
    <td>{{article.description}}</td>
    <td>{{article.status}}</td>
    <td>{{article.author.name}}</td>
    <td>{{article.moderator.name}}</td>
    <td>{{article.created_at}}</td>
    <td>
        <router-link :to="`/admin/blogs/${article.id}`">View</router-link>
    </td>
    </tr>

which is now working and gives me error below

[Vue warn]: Error in render: "TypeError: article.author is undefined"

I have also tried the below

 <td>{{article.author[0].name}}</td>

and got the below error which is same as above.

[Vue warn]: Error in render: "TypeError: article.author[0] is undefined"

where am i going wrong ?

18 Mar
4 months ago

princeoo7 left a reply on No Redirection On 401 With Following Code.

@tykus is my route.beforeEach wrong ?

17 Mar
4 months ago

princeoo7 left a reply on No Redirection On 401 With Following Code.

@TYKUS - i was just about to post my before each code ....

router.beforeEach((to, from, next) => {
    const requireAuth = to.matched.some(record => record.meta.requireAuth);
    const currentUser = store.state.currentUser;
    if (requireAuth && !currentUser) {
        next("/login");
    } else if (to.path == "/login" && currentUser) {
        next("/");
    } else {
        next();
    }
});

this is what i am doing but it still fails : (

princeoo7 left a reply on No Redirection On 401 With Following Code.

@TYKUS - yes and the problem was some but new error arise and still stucked is somewhat same condition.

id my store.js i have:

export default {
        state: {
        currentUser: user,
    }
}

now if the user is logged in then the api and view works. but if i try to visit it when the user is logged out or the token has expired, i get following error

[Vue warn]: Error in mounted hook: "TypeError: context.state.currentUser is null"

i understand that this error is because the user is undefined when they are not logged in but how to check this ( as i asked before ) before the view requested and not after loaded. currently i can see my view but just no data is displayed.