ApexLeo

Member Since 10 Months Ago

Experience Points
4,580
Total
Experience

420 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
28
Lessons
Completed
Best Reply Awards
1
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.

  • Community Pillar

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

Level 1
4,580 XP
Dec
02
2 days ago
Activity icon

Replied to Laravel Image Upload Issues ( Experts Please )

@loyd here is the code

public static function StoreImage($image, $fieldName, $path)
    {
        $thumbData = [];
        $imageData = [];

        if (isset($image)) {
            $fileNameWithExt = $image->getClientOriginalName();
            $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            $extension = $image->getClientOriginalExtension();
            $fileNameToStore = time() . '.' . $extension;

            $storagePath = storage_path('app/'.$path);
            if(!File::isDirectory($storagePath)) { File::makeDirectory($storagePath, 0777, true, true); }

            $imageData = self::generateImage($image, $path, $fileNameToStore);
            $thumbData = self::generateThumbnail($image, $path, $fileNameToStore);

        } else {
            return false;
        }

        return $data = [
            'image' => $imageData,
            'thumb_image' => $thumbData,
            'type' => mime_content_type($storagePath.$fileNameToStore),
            'extension' => strtolower($extension),
        ];
    }

    private static function generateThumbnail($image, $path, $fileNameToStore)
    {
        $fileNameToStore = 'thumb_' . $fileNameToStore;
        $image = self::createThumbnail($image, $path, $fileNameToStore, 200, 200);

        return $data = [
            'imageName' => $fileNameToStore,
            'path' => $path,
            'size' => $image->filesize(),
        ];
    }

    public static function createThumbnail($image, $path, $fileNameToStore, $width, $height)
    {
        $image = Image::make($image)->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
        });
        $image->save(storage_path('app/' . $path . $fileNameToStore)); // at this point my page goes blank
        return $image;
    }

    private static function generateImage($image, $path, $fileNameToStore)
    {
//        $image = Image::make($image);
//        $image->save(storage_path('app/' . $path . $fileNameToStore));  // at this point my page goes blank
        $image->storeAs($path, $fileNameToStore);

        return $data = [
            'imageName' => $fileNameToStore,
            'path' => $path,
            'size' => filesize(storage_path('app/' . $path . $fileNameToStore)), // $image->filesize(),
        ];
    }

and here is the validation for image

'nullable|image|mimes:jpeg,jpg,png|max:2048' // this is not working saying image must be an image
'nullable|mimes:jpeg,jpg,png|max:2048' // this one is working fine
Dec
01
3 days ago
Activity icon

Replied to Is There Laracasts Mobile (android) App??

@sergiu17 thanku for your response

Activity icon

Started a new Conversation Is There Laracasts Mobile (android) App??

Hi everyone. is there any mobile app for this platform ??

Activity icon

Started a new Conversation Laravel Image Upload Issues ( Experts Please )

Hi Everyone, i am having issues with image upload functionality. Let me just tell u that i am able to upload images to server so i am not here for enctype problem. lets just go through the point i have, and m also using laravel intervention.

  1. When i try to save my image using saveAs function it save my image perfectly.
  2. but when i try to save my image with intervention $image->make() it turn my webpage to blank i mean my request stop and show a complete white page. and it happen only when i try to save image greater then 200 - 300 kB file. but intervention work fine with 20-80 kB file.
  3. now lets get to laravel image validation. when i use 'image' => 'image|mimes:jpg.etc' it gives me error Image must be an image but when i remove "image" validation and only remain "mimes" validation then there is no error and image is saved perfectly. and again its happening with 200-300 kB file which is jpg and woking fine on 20-80 kB file which in png.

anyone have any suggestions??

Nov
18
2 weeks ago
Activity icon

Replied to Laravel Telegram Api Integration

Hi, @tisuchi thank you for your quick response. i am already doing few of these things. but it didn't answer any of my question

Activity icon

Started a new Conversation Laravel Telegram Api Integration

Hello Laracasts, I am having an issue to get a telegram user id of a user using his/her username. Also, there are few scenarios that I want to know is that possible or not using PHP telegram api.

  1. if we have a username of any user, can we get his/her user id from @userinfobot?
  2. can we receive messages from the user using Bot? i mean two way communication. or check if which user has join our channel etc.
  3. how to hide input field from a bot so no one can reply?
  4. how to add predefined buttons instead of an input field? like most channels groups are doing.
  5. also, if a user adds our bot can we programmatically press the join button for him?

it will be a great help if anyone can answer the questions. Thank you.

Oct
23
1 month ago
Activity icon

Awarded Best Reply on Laravel Scheduler: Log File Not Working, Issue With Log.

Ok guys i found the issue. The issue has nothing to do with scheduler.

In Config directory i have a file for my domain specific variables. there i was using

<?php
return [
    'app' => [
        'logo' => [
            'favicon' => asset('path_to_icon'),
            'logo' => asset('path_to_logo'),
        ],
    ],
]

"asset()" function to set my domain logos and icons and that "asset()" was the key to this issue. don't use such functions in config file because that don't just interrupt schedulers but also no artisan command can be run.

maybe it has to do something with service containers that they don't get registered at that time that is why they throw error. maybe i don't know that for sure.

Activity icon

Replied to Laravel Scheduler: Log File Not Working, Issue With Log.

Ok guys i found the issue. The issue has nothing to do with scheduler.

In Config directory i have a file for my domain specific variables. there i was using

<?php
return [
    'app' => [
        'logo' => [
            'favicon' => asset('path_to_icon'),
            'logo' => asset('path_to_logo'),
        ],
    ],
]

"asset()" function to set my domain logos and icons and that "asset()" was the key to this issue. don't use such functions in config file because that don't just interrupt schedulers but also no artisan command can be run.

maybe it has to do something with service containers that they don't get registered at that time that is why they throw error. maybe i don't know that for sure.

Oct
22
1 month ago
Activity icon

Replied to Laravel | Check Output Before Render It To Browser

@msaied there is a blade directive @once that make sure that the scripts is used once on a page, i hope that directive maybe helpful to you.

Here is the link to document: https://laravel.com/docs/8.x/blade#the-once-directive

Activity icon

Replied to Laravel Scheduler: Log File Not Working, Issue With Log.

@snapey no i configured the scheduler in cpanel that call that scheduler.

Activity icon

Started a new Conversation Laravel Scheduler: Log File Not Working, Issue With Log.

Hi, i am having issue with laravel scheduler.

first of all, i want to confirm that my scheduler is working fine no issue i configured my cpanel its working.

Issue

  1. the issue is i am unable to run Log::info in my scheduler. and their is an error occurred on every scheduler run.
  2. even if my laravel scheduler function is empty that error still occur and i don't know why.

Code

  1. Error occur. even for default template.

    protected function schedule(Schedule $schedule)
    {
         $schedule->command('inspire')->everyMinute();
    }
  1. Error occur.

    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            Log::info('hello world');
           Log::channel('single')->info('hello world');
        })->everyMinute();
    }
  1. Error occur. even if scheduler is empty

    protected function schedule(Schedule $schedule)
    {


    }

** Error **

here is the error that is written to log/laravel.log file on every scheduler call


[2020-10-22 06:59:01] laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. 	{"exception":"[object] (InvalidArgumentException(code: 0): Log [] is not defined. at my_domain/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:192)
[stacktrace]
then stack trace here

[2020-10-22 06:59:01] laravel.ERROR: Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given, called in my_domain/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php on line 65 {"exception":"[object] (TypeError(code: 0): Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given, called in my_domain/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php on line 65 at my_domain/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:120)
[stacktrace]
Oct
15
1 month ago
Activity icon

Replied to Laravel Map Request To FormRequest

@sinnbeck you are right after testing i find out it was my fault your answer is working fine.

@automica I did mark sinnbeck answer as best answer as you suggested.

but @sinnbeck i request you to add the link given below in your best answer so other people can see other perspective and know how to validate this new request.

Thanks for both of u guys.

here is the Link: https://laracasts.com/discuss/channels/code-review/is-there-a-way-to-make-a-form-request-from-another-request?page=1

Oct
12
1 month ago
Activity icon

Replied to Laravel Map Request To FormRequest

Thanks for your help and support @sinnbeck

Activity icon

Replied to Laravel Map Request To FormRequest

@sinnbeck ok i have found the answer to the problem. Here Is The Solution

$userRequest = UserRequest::createFrom($request);

this syntex only return instance of UserRequest. it didn't validate the the request it self. One must have to validate separately by using old fashion syntex like this.

$this->validate($userRequest, $userRequest->rules())

hope this may help others.

You can see the original answer Here

Activity icon

Replied to Laravel Map Request To FormRequest

@sinnbeck hi. as u mention in the last reply i did that but it return a simple Request Instance not UserRequest instance. or is there something that i am missing.

$userRequest = Request::createFrom($request, new UserRequest());
Activity icon

Replied to Laravel Map Request To FormRequest

@sinnbeck yes i could. but i want to validate the Request comming from the newStore(Request $request) plus i am also mutating and adding values in UserRequest. so is their any way i can Map the Request to UserRequest?

Activity icon

Replied to Laravel Map Request To FormRequest

@sinnbeck because i am using UserRequest for web, now for api i am receiving different name parameters.

what i am trying to do is to receive Request then mutate the request and pass that Request to UserRequest. so that i can use the same request for both functions.

Activity icon

Started a new Conversation Laravel Map Request To FormRequest

Hi i am trying to map my Request instance to FormRequest as an example here is the code.


public function store(UserRequest $request)
{
	// code ...
}

now i want to call above mention store function from another function that accept only Request like this.


public function newStore(Request $request)
{
	$this->store($request) //  <= here is the issue that function accept FormRequest while i have only Request;
}

please help

i alsoe tried this


public function newStore(Request $request)
{
	$userRequest = new UserRequest([], $request->all());
	$this->store($userRequest);
}

still not working

Oct
08
1 month ago
Activity icon

Replied to Target Class [App\Http\Controllers\MyController] Does Not Exist. Laravel 8

@michaloravec ok i change the name of My controller and file. it worked. but when i revert back to its orignal name it says the same error

Activity icon

Started a new Conversation Target Class [App\Http\Controllers\MyController] Does Not Exist. Laravel 8

i have a Controller MyController in my Controllers Folder

My Route is

Route::resource('my', \App\Http\Controllers\MyController::class);

My Controller


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MyController extends Controller
{
	// My Resource Functions ...
}

All my other routes working fine. this route was working fine as well but now somehow it says class not found. While i can Navigatre to class by clicking on route and vice versa.

Aug
29
3 months ago
Activity icon

Replied to Laravel 7 - Form With A Custom CSS Doesn't Select File

@singh use &lt; instrad of opening angle bracket for the <form> tag

Aug
15
3 months ago
Activity icon

Replied to Pre-selecting Values With Select2

@acrm use this in your html select.


<select>
@foreach($subcategories as $subcategory)
	<option value="{{ $subcategory->id }}" {{ $requirement->source->name == $subcategory->name ? 'selected' : '' }}>{{ $subcategory->name }}
@endforeach
</select>

if u have multiple values to select then use this. i assume u have name array in $requirement->source->name


<select>
@foreach($subcategories as $subcategory)
	<option value="{{ $subcategory->id }}" {{ in_array($subcategory->name, $requirement->source->name) ? 'selected' : '' }}>{{ $subcategory->name }}
@endforeach
</select>
Activity icon

Replied to Where Are You All From?

Multan, Pakistan

Aug
14
3 months ago
Activity icon

Replied to Laravel Mail To Mailtrap From Sharedhosting.

@sinnbeck @snapey here is something that i found

i have an email [email protected]

when i send email to [email protected] using mailtrap config but with mailer "sendmail" it send mail to [email protected] instead of mailtrap account

here is config


MAIL_MAILER=sendmail
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=**************
MAIL_PASSWORD=**************
MAIL_ENCRYPTION=tsl
[email protected]**************
MAIL_FROM_NAME="${APP_NAME}"

even though this has nothing to do with my issue this is just for information

Activity icon

Replied to Laravel Mail To Mailtrap From Sharedhosting.

@snapey my passowrd didn't contain # or any space but for safe side i did that as u mentioned but result is same.

@sinnbeck i also try sendmail, mailgun, smtp but none of them work and as u mentioned earlier i did contact my hosting provider they say they allow SMTP on their server with PORTS 25, 465, 587 and 2525. but none of the ports work

Activity icon

Replied to Laravel Mail To Mailtrap From Sharedhosting.

@sinnbeck hello sinnbeck thnaks for your time i also tried 25 or 465 or 587 or 2525 none of them work and all give the same error with or without tls encription

i will try contacting them

Activity icon

Started a new Conversation Laravel Mail To Mailtrap From Sharedhosting.

Hello everyone, i am having an issue sending mail from laravel to mailtrap.

for your info.

  1. i have run my mailtrap configurations on local it work fine.
  2. i have run my gmail configurations on shared hosting they work fine as well.
  3. when i run my mailtrap configurations on shared hosting here come the issue.

Error Screenshot on shared hosting

Screenshot Link

Mailtrap config (work fine on local, but issue on server)

 
MAIL_MAILER=smtp // i have also tried snedmail, mailgun etc.
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=**************
MAIL_PASSWORD=**************
MAIL_ENCRYPTION=tls
[email protected]**************
MAIL_FROM_NAME="${APP_NAME}"

Gmail Config (work fine on server)


MAIL_MAILER=sendmail
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]************
MAIL_PASSWORD=************
[email protected]************
MAIL_FROM_NAME="${APP_NAME}"
Activity icon

Replied to Livewire With SweetAlert2

@sunnyboy hello brother. i have not personaly use livewire but i watched this video which show how to submit form.

may be that prove helpfull to u Laravel Livewire

@sunnyboy u can use the same logic to display sweet alert

Activity icon

Replied to Need Help To Understand Flock() Of Core Php.

@jaynarayan instead of file_put_contents why don't u use fwrite.

like this example



<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

hope that help

Aug
12
3 months ago
Activity icon

Replied to Form Submit Leads To 404 Page Not Found

@snapey @sinnbeck i am not sure about that but i never change my VerifyCsrfToken middleware and if i missing a csrf token on my post request it sometimes through 404 error. can't say anything about it why it do that.

Aug
11
3 months ago
Activity icon

Awarded Best Reply on Form Submit Leads To 404 Page Not Found

@julifighter96 by looking at your form u didn't add @csrf in your form

try adding @csrf


<form method="post" action=" your route ">
	@csrf
	... rest of the form fields
</form>
Activity icon

Replied to Form Submit Leads To 404 Page Not Found

@julifighter96 by looking at your form u didn't add @csrf in your form

try adding @csrf


<form method="post" action=" your route ">
	@csrf
	... rest of the form fields
</form>
Activity icon

Replied to How To Add The Pagination On Index

@webfuelcode i assume u hvae a model name Thread.

did u paginate the Thread model like this.


$threads = Thread::paginate(); // default is 15

$threads = Thread::where( 'your condition' )->paginate(20) // you can assign rows per page;
Activity icon

Replied to Laravel API Controller Add Paginate Meta Values To Response

Senario

@brandon.css if you want to return single row then use new ModelResource($modele) and if you want to return a collection then use ModelResource::collection($models)


// for single record
return new ModelResource( Model::latest()->first() );

// for collection with or without pagination
return ModelResource::collection( Model::latest()->paginate() );

if you use second approach it will add meta tags it self as u mention above .

Problem

Problem is when u use response()->jason() then meta tags won't work

Solution

in that senario this is what i do first of all i create two resource classes for the same model as you can see.

.
+-- Http
|   +-- Resources
|   |   +-- Store (Store is model name in your case)
|   |   |   +-- StoreCollection
|   |   |   +-- StoreResource

for more info about ModelCollection & ModelResource see this Laravel Api Resource

now in StoreResource write your code as you normally do


    public function toArray($request)
    {
        return [
            "id" => $this->slug,
            "name" => $this->name,
            // etc
        ];
    }

now in StoreCollection this is what i do to paginate my model.


    public function toArray($request)
    {
        return [
            'data' => StoreResource::collection($this->collection),
            'pagination' => [
                "current_page" => $this->currentPage(),
                "first_page_url" =>  $this->getOptions()['path'].'?'.$this->getOptions()['pageName'].'=1',
                "prev_page_url" =>  $this->previousPageUrl(),
                "next_page_url" =>  $this->nextPageUrl(),
                "last_page_url" =>  $this->getOptions()['path'].'?'.$this->getOptions()['pageName'].'='.$this->lastPage(),
                "last_page" =>  $this->lastPage(),
                "per_page" =>  $this->perPage(),
                "total" =>  $this->total(),
                "path" =>  $this->getOptions()['path'],
            ],
        ];
    }

now in controller


// if you want to return single record
return response()->json( new ModelResource( Model::latest()->first() ), 200 );

// and for collection with pagination
return response()->json( new ModelCollection(Model::paginate()), 200 );


// you can also add other info
return response()->json([ 'data' => new ModelCollection(Model::paginate()), 'success' => true ], 200 );

for more info about pagination in StoreCollection visit this link Laravel Pagination

Activity icon

Replied to Classic Login And Passport Login At Same Time

@andyandy you want to use the web login but also want to login using api token. i have'nt work with passport but work with JWT

for that i recommend you to watch this tutorial https://www.youtube.com/watch?v=6eX9Pj-GhZs

this link will show u how u can login from api jwt while keeping the classic login. maybe that prove helpfull to u and u can find your answer in some way

Activity icon

Awarded Best Reply on On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

@sinnbeck for the time being i removed soft delete functionality from my AdviceMedia and migrate:fresh because it was not necessary.

and for future reference it was the mistake on my side i accidentally softdeleted the model in my controller which i added for testing purpose and forget to remove. which is why all of my data become deleted and was unable to fetch.

to fetch softdeleted data u need to query like this


$adviceMedia = AdviceMedia::withTrashed()->get();

for better understanding on soft delete visit this link laravel soft delete

@tisuchi @sinnbeck sry guys for bothring u but thanks for your help

Activity icon

Replied to On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

@sinnbeck for the time being i removed soft delete functionality from my AdviceMedia and migrate:fresh because it was not necessary.

and for future reference it was the mistake on my side i accidentally softdeleted the model in my controller which i added for testing purpose and forget to remove. which is why all of my data become deleted and was unable to fetch.

to fetch softdeleted data u need to query like this


$adviceMedia = AdviceMedia::withTrashed()->get();

for better understanding on soft delete visit this link laravel soft delete

@tisuchi @sinnbeck sry guys for bothring u but thanks for your help

Activity icon

Replied to On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

@tisuchi @sinnbeck i did found the problem but i don't know why its happening.

the problem is SoftDelete

when i removed

use softDelete
from my model it start fetching data. i don't why its happening i also have SoftDelete on all my other models but they are working fine.

hope u know something about this.


namespace App\Models\Advice;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AdviceMedia extends Model
{
    use SoftDeletes; // this line is the issue

    protected $table = 'advice_media';

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];



    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */
    public function advice()
    {
        return $this->belongsTo(Advice::class);
    }
}

Activity icon

Replied to On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

@tisuchi i created my model and migration using php artisan


php artisan make:model AdviceMedia -mc
Activity icon

Replied to On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

@tisuchi yes i did try assigning the table name to the model but still return Null.

@sinnbeck here is my Model AdviceMedia


namespace App\Models\Advice;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AdviceMedia extends Model
{
    use SoftDeletes;

    protected $table = 'advice_media';

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];



    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */
    public function advice()
    {
        return $this->belongsTo(Advice::class);
    }
}

Activity icon

Started a new Conversation On Retrieve: Eloquent Model Return Null While Query Builder Working Fine

I have a Model AdviceMedia

when i try to fetch data from this model using this syntex it return null

$adviceMedia = AdviceMedia::all(); // return null
$adviceMedia = AdviceMedia::where('id', '=', 1)->first(); //return null 

the above code return null with all other retrieving logic. even though records exists in database

on the other hand if i use QueryBuilder Sytex it work fine


$adviceMedia = DB::table('advice_media')->get() // return correct data

now thats not it.

if i try to save/create new record using Eloquent Model it work fine with out any issue. (obviously cannot update)


$adviceMedia = AdviceMedia::create($data)  // save data successfully

also if i try to fetch this model using relation like

$advice = Advice::with('adviceMedia')->get();

the AdviceMedia relation return null.

All the other models are working fine.