tareenmj

tareenmj

Member Since 2 Years Ago

Experience Points 5,120
Experience Level 2

4,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 34
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

05 Oct
1 year ago

tareenmj left a reply on How To Present Contents Of A File (stored On My Project) In A Blade File?

@jlrdw I am attempting to read file contents of a file (already stored in my Storage) and then place that in a view.

tareenmj left a reply on How To Present Contents Of A File (stored On My Project) In A Blade File?

@jlrdw I attempted to use getContents() method but it says that 'Call to a member function getContents() on a non-object'.

I am receiving my file as such:::

        $path = $user->cv()->first()->path;
        $fileName = explode("/", $path)[1];
        $extension = explode(".", $path)[1];
        $uploaded = Storage::get($path); //if i do dd($uploaded) it does output the file (a representation of it)
        dd($uploaded->getContents());

tareenmj started a new conversation How To Present Contents Of A File (stored On My Project) In A Blade File?

I have a view with a bunch of HTML, and I would also like to present the user's resume they posted before. I have a link from which the user can download their resume:

Route::get('resumeDownload', function() {
    $user = Auth::user();
    if ($user->cv()->count() != 0) { //if the user has a CV uploaded
        $path = $user->cv()->first()->path;
        $fileName = explode("/", $path)[1];
        $extension = explode(".", $path)[1];
        $uploaded = Storage::get($path);
        return (new \Illuminate\Http\Response($uploaded, 200))->header('Content-Type', 'application/msword'); //extension not working properly I know, don't know how to resolve it
    } else { //if the user has no CV uploaded
        return view('errors/404', ['notifications'=>$notifications, 'user'=>$user]);
    }
});

But now my CV stored in that path, I would like to retrieve the contents of it and display it in my blade file with my other html. Any suggestions how I would go about doing this?

public function generic_function(){
    return view('sampleView', ['user'=>$user]); //I need to pass contents of the file into this view so I can display it
}

And finally How would I show it in my view? (Assuming I pass the contents of the file as a variable)

<html>
<body>
<!-- 
Random HTML pieces of code

-->
</body>

{{$resume}} <!-- WOuld it be something like a simple echo statement?? -->
</html>

08 Sep
1 year ago

tareenmj left a reply on How Do I Change The Max_post_size And The Max_upload_size In Laravel 5.0?

@JackJones yea but I can't seem to locate the file where I would change the upload_size, or can I just do it on a route. I read that php has a php.ini file but i can't find it on my Laravel app

tareenmj started a new conversation How Do I Change The Max_post_size And The Max_upload_size In Laravel 5.0?

I need to be able to upload files my user choses to upload. I was able to accomplish this, thanks to Laravel's filesystems but I am unsure about what is the max size the user can upload, and how I can change this property. Could anyone help me out?

14 Aug
1 year ago

tareenmj started a new conversation Validating An Array Of Inputs In Laravel 5.0

I have a table, where the user can choose to add/delete rows. These rows have two input fields (TB1_a[] and TB1_b[]). I would like to make my rules so that TB1_a[0] is only required if TB1_b[0] is not null. So I created my rules as:

foreach ($this->request->get('TB1_a') as $key => $val) { 
    $rules['TB1_a[' . $key .']'] = 'required_with:TB1_b[' . $key .']'; 
    $rules['TB1_a[' . $key .']'] = 'required_with:TB1_b[' . $key .']'; } 
return $rules;

However, for some reason, this is unable to work and always makes my data valid. Could anyone please help me in this case?

tareenmj left a reply on How Do I Validate Array Inputs In Laravel 5.0

@ChristophHarms yup, I was suggested to go through each of the input fields and manually add the rules, but it's just an annoying procedure. Guess Laravel 5.1 would have helped far more

tareenmj started a new conversation How Do I Validate Array Inputs In Laravel 5.0

I have a table, where the user can fill in information. However, the user can add rows and/or delete rows. I used a cloning function for that.

My html looks like:

<input type="text" class="form-control" name="TB1_a[]">
<input type="text" class="form-control" name="TB1_b[]">

As you can see, it is an array input. So if the user adds a row, I'll have two values stored in TB1_a[] and TB1_b. Now, I would like to make my rules so that if the user enters information inside TB1_a[0], I would like to make TB1_b[0] required, but valid if both TB1_a[0] and TB1_b[0] are empty.

My validation rules:

'TB1_a.*' => 'required_with:TB1_b.*',
'TB1_b.*' => 'required_with:TB1_a.*'

However, these rules are unable to detect that I am referring to an array, meaning Laravel does not detect the '.*'. I would also like to point out that this logic was working perfectly with Laravel 5.4, but I have had to downgrade my Laravel and now it stops working. Any help please?

03 Aug
1 year ago

tareenmj started a new conversation How To Pre-select Select Statements In Laravel

I have a select statement with a large number of options to select. I am retrieving all of the options from my back-end and filling them in. However I would also like to select an option, which I also pass in from my backend. My code is as follows:

@for($i=0; $i<sizeof($info['userInfo']['courses']); $i++) //
                <tr class="table_row">
                    <td><select class="form-control" name="TB1_instructions_course[]" id="course" required="" value='{{$info['userInfo']['courses'][$i]}}'>
                            <option value="">Course</option>
                            @foreach($info['staticInfo']['courses'] as $course) //pull in static data
                            <option>{{$course['course']}}</option>
                            @endforeach
                        </select></td>
                    <td><input type="text" class="form-control" placeholder="C01" name="TB1_instructions_section[]" id='section' required="" value='{{$info['userInfo']['courses'][$i]}}'></td>
                    <!-- the rest of the table-->


Now the text field works perfectly and populates it accordingly, but I am unable to select the appropriate option in my select input. Any help? Can I do this without using jQuery or javascript?

27 Jul
1 year ago

tareenmj left a reply on Use Regex To Allow For Alphabetic Characters, Hypens, Underscores, Spaces, And Numbers

I was originally using alpha_num as a validation method, and when I did include spaces, it gave me an error.

tareenmj started a new conversation Use Regex To Allow For Alphabetic Characters, Hypens, Underscores, Spaces, And Numbers

I would like to validate using Laravel for a unique situation. The field I am authorizing is the name of a book. So it can have alphabetic characters, numeric characters, spaces, and hypens/underscores/any other key. The only thing I don't want it to have is spaces at the beginning, before you enter any key. So the name can't be " L", notice the space, whereas "L L L" is completely acceptable. Could anyone help me in this situation?

So far I got a regex validation as such: regex:[a-z{1}[A-Z]{1}[0-9]{1}]

I'm unsure how to include the other restrictions.

25 Jul
1 year ago

tareenmj left a reply on How To Use Authentication Using Username Instead Of Email

@jlrdw Yea I already placed that, but it still does not have any effect, is there a possible problem with my View file?

tareenmj started a new conversation How To Use Authentication Using Username Instead Of Email

I want to create an app where I Log in the username based on username, instead of email address. Since I am a beginner to Authentication, I simply ran the php artisan make:auth and the migrate commands.

I edited my Login controller by placing a method as such:

class LoginController extends Controller
{

use AuthenticatesUsers;
    
    public function username(){
        return 'username';
    }

//the rest of the controller code

Now my Login Blade file is as:

<form class="form-horizontal" method="POST" action="{{ route('login') }}">
                        {{ csrf_field() }}

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

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

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

//followed by the rest of the html.

However, as soon as I type in the name and the password, it doesn't allow me to be logged in, and does nothing. I am unsure about what I am doing wrong here, can somebody please help?

22 Jun
1 year ago

tareenmj started a new conversation Mimes Validation Not Working Correctly In Laravel

My webpage contains a file for upload, and I want the file uploaded to only be either pdf, doc or docx.

My form tag also has enctype="multipart/form-data" and has files="true"

My html looks like:

<div id="cv_upload" class="row">
    <div class="col-xs-12">
          <input type="file" name='cv'>
    </div>
</div>

The $rules array associated with this is as follows:

'cv' => 'mimes:pdf,doc,docx|required'

And finally my messages looks like:

'cv.required' => 'A selection for C.V. is required before proceeding.',
'cv.mimes' => 'CV must be of the following file type: pdf, doc or docx.'

The only problem with this is, even after I upload a pdf or doc, the message I receive is the one for required. I have no idea why this isn't working as expected. I also tried removing the 'application/' but that yields no success either. Please help.

19 Jun
1 year ago

tareenmj started a new conversation I Need To Remove All Elements From An Associative Array Based On A Variable Name

I am reading input from the user (in Laravel) and have rules associated to each of those inputs. If the user selects a checkbox (for that specific table), I would like to remove all the rules from the $rules associative array for that table.

To better illustrate, I have created two arrays mimicking the behaviour.

My input array is as follows:

$input = array("TB1_course" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
                            ],  
          "TB1_section" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
                            ], 
          "TB1_checkbox" => "1",
          "TB2_course" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
                            ],
          "TB2_checkbox" => "0"
);

$rules= array(
    'TB1_course.*' => 'required_with',
    'TB1_section.*' =>'required_with',
    'TB2_course.*' =>'required_with'
);

You can see from the input array that TB1_checkbox has a value of 1. If it has a value of 1, I would like to remove all the rules associated with TB1 (i.e. remove the elements in $rules with a key containing 'TB1').

I attempted to do as such, and was partially successful. My code looks like:

foreach ($input as $key=>$value){//go thru every element of the inputs
    if ((strpos($key, 'checkbox')!==false) && $value==1){//if it contains 'checkbox' 
//and checkbox is selected

        $table_name= substr($key, 0,3);//name of table

        //now go thru $rules and remove all elements which contain a word of $table_name

        $rules=array_filter($rules, function($x){
            return strpos($x, $table_name)!==0;//problem lies here
        }, ARRAY_FILTER_USE_KEY);
    }
}

However my code isn't working. The strpos() function is unable to read the $table_name variable, and leads to problems. If I manually pass in a string, it ends up working (i.e. 'TB1' instead of $table_name), but I have to have the flexibility of checking all my tables (so the rules containing 'TB2' have to be removed if "TB2_checkbox" has a value of 1). Is there any way to solve this issue?

Thank you for the help.

16 Jun
1 year ago

tareenmj started a new conversation How Do I Apply Custom Validation On An Array?

My problem is fairly complex and kind of difficult to explain with text, so I will try my best.

I have three inputs, all as arrays, 'A' 'B' 'C'. I also have a checkbox input 'D' (not an array). Every element in A has to be required if the corresponding element in B or C is non-empty, BUT, if D has a value of 1, A shouldn't be required even if the corresponding elements in B or C are non-empty. If A[1] is empty, and B[1] is empty but C[1] is non-empty, I would like A[1], only, to be required.

I created some rules to try and solve this, but i'm unsure how to solve it.

]);

$validator->sometimes('A.*', 'required', function($input){
        if ($input->D==1){//if checkbox D is checked, don't make A required regardless of anything else
            return false;
        }
        if (($input->B!=null) || ($input->C!=null)){//instead of doing it for the individual elements it will make A required if any element of B or C is non-empty
            return true;
        }
        return false;
    });


tareenmj started a new conversation How Do I Call A Public Function Inside Of My Controller?

I have a problem with being able to call a function I defined in my controller.

My controller has defined functions which I would like to call from a string.

public function store(Request $request) {
        $data = $request->except('_token');

    $name = "form1_sections/" . $data['nextTab'] . "_form";
    parse_str($data['inputs'], $output);
    $rules =  $this->call_user_func($data['currentTab']);
    $validator = Validator::make($output, $rules);

    if ($validator->passes()) {
        return ["view" => view("$name")->render(), "isValid" => true];
    } else {
        return ["isValid" => false, "msg" => json_encode([
                'errors' => $validator->errors()->getMessages(),
                'code' => 422
            ])
        ];
    }
    }

    function section1() {
        return [
            'startDate' => 'required| date',
            'endDate' => 'required| date|different:startDate',
            'cv' => 'mimes:pdf,doc,docx'
        ];
    }

$data['currentTab'] returns a string like section1, and I would like to invoke section1() function whenever that is the case. Any help?

tareenmj left a reply on Validation Working In Web.php But Not In My Controller

no luck, it doesn't work. I'm trying to find a way to do this but even after researching, can't find a lot explaining this.

tareenmj started a new conversation Laravel Validation: Make A Field Required If Other Fields Are Present BUT Don't Make It Required If A Certain Field Has A Specific Value

I have a bunch of inputs on my form, and the field under consideration has various validation requirements. To simplify, I have created an analogy:

I have inputs A, B, C and D. 'A' should be required if B and C are present, but not required if input 'D' is a value of 1 even if B and C are present. The same requirements are present for inputs 'B' and 'C'.

My initial guess was: A => 'required_with:B,C | required_if:D,0' but this doesn't really work.

I'm terrible with custom validation, so if a step-by-step method of a custom validator is needed, can you please provide a full code?

Thank you!

tareenmj left a reply on Validation Working In Web.php But Not In My Controller

@Snapey after doing a bit of research it turns out, I need a use Validator at the top of my controller, if I am using the Validator::make. I seem to be having one other problem however, the section1() functions need to be placed in the web.php, when I remove them from there it gives me an error. Is there any way I can call those functions, if they are stored only in my controller? Thanks a bunch

tareenmj left a reply on Validation Working In Web.php But Not In My Controller

An error of: master.js:76 POST 500 (Internal Server Error)

and a warning of: master.js:76 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Any idea? Thanks for your help!

tareenmj left a reply on Validation Working In Web.php But Not In My Controller

My ajax request ends up breaking and giving me a message for 'error'

tareenmj started a new conversation Validation Working In Web.php But Not In My Controller

Hi!

I had a problem with validation. For testing purposes, I had all my validation logic stored inside my routes file (web.php), but I attempted to move it into my controller but for some reason it stops working. My code was working perfectly when it was placed in the routes file.

My code is as follows:

15 Jun
1 year ago

tareenmj started a new conversation Laravel: Do Validation Upon Two Separate Conditions

I have a table in my html form, where the user is free to add as many rows as they would like. Underneath the table I have a checkbox, which when checked indicates the user has no inputs.

I have a bunch of inputs in Laravel which are in an array (so it can name[0] and name [1] or just name[0] depending on how many rows the user added). I also have a checkbox, which makes all my inputs disappear, and I wouldn't like to make any field required if the user checked it.

My current rules are:

[ 'TB1_course.' => 'required_if:TB1_checkbox, 0|required_with:TB1_section.,TB1_session.,TB1_reqElec.', 'TB1_section.' => 'required_if:TB1_checkbox, 0|alpha_num', 'TB1_session.' => 'required_if:TB1_checkbox, 0' ]

My validation rules required:

(1) If the user selects the checkbox, I would like to make no field in the entire table required (regardless if those inputs are empty or not)

(2) If the user didn't select the checkbox and left one row entirely blank (i.e. TB1_course[0], TB1_section[0], and TB_session[0] empty OR supplied TB1_course[0], TB1_section[0], TB1_session[0] but left TB1_course[1], TB1_section[1] and TB1_session[1] empty), inputs are valid.

(3) If the user didn't select the checbox and also gave missing info on the same row (i.e. TB1_course[0] isn't empty but TB1_section[0] and TB1_session[0] are empty), make it invalid.

I am unsure how to go about this, since I also have to worry about indices. I'm a beginner in validation, so please excuse me if I am asking a very basic problem. Any help is greatly appreciated.

08 Jun
1 year ago

tareenmj left a reply on Required Only If A Checkbox Is Not Checked

@Screenbeetle can't I just do something like

$rules= [ 'TB1_course.*' => 'required_if: TB1_checkbox,0' ] ?

tareenmj started a new conversation Required Only If A Checkbox Is Not Checked

I am a bit of a beginner in Laravel, and I had some trouble with validation. I want to make a field required only if the value of the a certain checkbox is 0. My rules currently are:

$rules=[
    'TB1_course.*' => 'required'
];

My checkbox input html is as such:

I gave a hidden input just so that if the user does not select the checkbox, I receive a value of 0. My TB1_course is an array of inputs, since I used a clone function in jQuery.

Is there an easy way to make TB1_course required only if TB1_checkbox is 0?

Thank you for all your help!

tareenmj started a new conversation How Do I Receive The Error Messages From Validation Upon An Ajax Request

I am not the most proficient at using Laravel, so I stumbled upon some issues with validation. I am doing an Ajax request to validate a section of a form, and if it the user gave valid information, I am replacing the html inside the form tag with the next view (the next section of the form). If they gave in invalid information, I don't want to change the html but rather just present the error messages. I only have one form tag, but I'm replacing the html content of the form if user gives valid info.

My web.php (i'm using closures):

$('#form').on('submit', function (e) { var formData = $('#form').serialize(); e.preventDefault(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: 'POST', url: '/roa', dataType: 'json',

        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID}, //also need to pass in related Tab ID, and also tabID
        success: function (data) {

            if (data.value===1){//only doing for one section right now
                if (data.isValid){//if data is valid, return next view
                    $('#tabShow').html((data.view));
                }
                else{//if it isn't target the div id=errors and replace only error section
                    alert(data.isValid);
                    var errors=data.responseJSON;
                    alert(errors);
                    false;//prevent navigation
                }
            }
            else{
            $('#tabShow').html((data.view));}
        },
        error: function () {
            alert('error');
        }
    });

Route::post('/roa', function() { $m = Request::except('_token'); $name = "form1_sections/" . $m['nextTab'] . "_form"; //name of next view $name2 = "form1_sections/" . $m['currentTab'] . "_form"; //name of current view

parse_str($m['inputs'], $output);//to deal with json
$type= gettype($output);
if ($m['currentTab']=='section2'){//since I was only working with one section
    $rules = [//rules for that section
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){
        return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output, "type"=>$type, "isValid"=>true]; //if valid, then pass next view
    }
    return ["view" => view("$name2")->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output, "type"=>$type, "isValid"=>false]; //if invalid, how do I pass error messages html?
}
return ["view" => view("$name") -> render()];//for all other sections

});

07 Jun
1 year ago

tareenmj left a reply on Returning A View With Previous Inputs Using Laravel And AJAX

@jlrdw I need to do back-end validation? In case the user gives in malicious data.

tareenmj left a reply on Returning A View With Previous Inputs Using Laravel And AJAX

@Snapey How would i use the old() function? I read that the withInput() method is a better alternative since the old() function I will have to adjust every single of my input fields

tareenmj left a reply on Returning A View With Previous Inputs Using Laravel And AJAX

I don't? When I am returning the view if an error is detected, it removes all the pre-filled input entries (i.e. "view" => view("$name2")->withInput($output)->withErrors($validator) -> render())

tareenmj started a new conversation Returning A View With Previous Inputs Using Laravel And AJAX

I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.

My Laravel Code:

Route::post('/roa', function() { $m = Request::except('_token'); $name = "form1_sections/" . $m['nextTab'] . "_form";//next view name $name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

$var= parse_str($m['inputs'], $output);//data from ajax is a string

if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now //to simplify the code. $rules = [ 'TB1_course.*' => 'required' ]; $validator=Validator::make($output, $rules); if ($validator->passes()){//if no error, return the next view return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output]; } return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output]; } return ["view" => view("$name") -> render()]; });

My Ajax request:

$('#form').on('submit', function (e) { var formData = $('#form').serialize(); e.preventDefault(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: 'POST', url: '/roa', dataType: 'json', data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID}, $('#tabShow').html((data.view)); }, error: function () { alert('error'); } }); });

I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.

tareenmj started a new conversation How Do I Validate All Of An Array's Elements?

I have received inputs from my front-end form, however since my tables are dynamic, my inputs looks like:

var $output = [ '_token' =>..... , 'TB1_course => [ '0'=> .., '1' => .., etc ], //other inputs ]

TB1_course can change in size depending on the user's input. I would like to make every element inside of TB1_course to be required. How would I do as such?

My initial guess was:

$rules= [ 'TB1_course' => 'required', //other rules for the rest of the inputs ]

Thanks for your help!

05 Apr
1 year ago

tareenmj started a new conversation Using Constraints On A One-to-many Relationship

So I have two tables in my database, Album and Artists. One artist can have multiple albums, so a one-to-many relationship. I defined my two models as:

class Artist extends Eloquent{

public $timestamps=false;

public function albums(){
    return $this->hasMany('App\Album','artist_id','id');
}

}

class Album extends Eloquent{ public $timestamps=false;

public function artist(){
    return $this->belongsTo('App\Artist','artist_id','id');
}

}

Now, I am trying to obtain all the albums associated with one artist, and order them alphabetically, but when I attempt to try this:

Route::get('/', function () { $x=\App\Artist::where('name','=','Drake')->get(); $album=$x[0]->albums->orderBy('name')->get(); echo $album[1]->name; }

It gives me an error saying that method orderBy does not exist. I also tried doing: $x=\App\Artist::orderBy('name')->get() and it worked perfectly. Thank you for the help!

04 Apr
1 year ago

tareenmj left a reply on Reading From A One-to-many Relationship Causing Errors

Thank you! Yea I think I'll go thru the docs in detail. Yea, that makes alot more sense.

tareenmj left a reply on Reading From A One-to-many Relationship Causing Errors

@starmatt Thank you for your reply, it made a lot more sense. I also wanted to know is it possible to work from the parent table without using a for loop to manually search through the child table? I.e.: if I have an artist_id and I would like to know all the albums associated with that one artist?

tareenmj left a reply on Reading From A One-to-many Relationship Causing Errors

I was able to solve it, I couldn't get my head around the collection object. If anyone would like to know how I solved it:

the $test=\App\Album::where('name','=','Horroscrope')->get() returns a collection object, to access the object inside the collection. You can do:

$x=\App\Album::where('name','=','Horrorscope')->get(); $test=$x[0]->artist()->get(); return $test[0]->name;

This will return the corresponding artist associated with the album.

tareenmj started a new conversation Reading From A One-to-many Relationship Causing Errors

So I defined a couple of models in Laravel (one was Album and one was Artist) as follows:

Album.php: class Album extends Eloquent{ public $timestamps=false; public function artist(){ return $this->belongsTo(Artist::class); } }

Artist.php: class Artist extends Eloquent{

public $timestamps=false;

public function albums(){
    return $this->hasMany(Album::class);
}

}

Now in my web.php: I ran these commands:

Route::get('/', function () { $artist= new \App\Artist; $artist->name='Eve 6'; $artist->save();

$album= new \App\Album; $album->name='Horrorscope'; $album->artist()->associate($artist); $album->save();

$test= \App\Album::where('name','=','Horrorscope')->get();

$x= $test->artist()->get(); return $x->name;

It gives me an error whenever I attempt to run this as: BadMethodCallException in Macroable.php line 74: Method artist does not exist.

Can anyone help in this category, I have no idea why it isn't working. I am attempting to get the artist associated with the $test variable, so if a user gives me an album name, I can retrieve the Artist directly. Any help will be appreciated.

03 Apr
1 year ago

tareenmj started a new conversation Many-to-many Relationship Between Two Tables Issue

So I wanted to create a many-to-many relationship between a table called 'albums' and a table called 'listeners', and I was able to do so successfully. I created the appropriate Eloquent classes for each and also created proper methods (i.e used the belongstoMany function). But now if I select a random album (depending on the user's input) and want to see all the listeners associated with that album, how would I go about doing so? Any help is appreciated!

28 Mar
1 year ago

tareenmj started a new conversation HTTP ERROR 500: When I Attempt To Upload A Laravel Project Onto My Remote Server

I am a bit of a beginner in Laravel and remote servers, etc, so please bear with me if I am asking something super obvious or simple.

I wanted to create a Laravel project on my webpage, so I connected to my server via Putty, and directly put the command through the command line of Putty. It created one (blog was its name) successfully, but it created the project inside of my webpage directory inside of its own folder called blog. I moved all the files and folders inside of blog to my main webpage directory through FileZilla. I did not change the Laravel code at all, it should show just the default start up page. When I visit my webpage, it throws an error like: HTTP ERROR 500. Just for curiosity, I visited my webpage/public (I know I do not have any route defined like this) and it threw a Laravel error like: NotFoundHttpException in RouteCollection.php line 161.

I want to upload an image so I also posted this question on stackoverflow, if you would like to have a look: http://stackoverflow.com/questions/43070849/laravel-on-my-remote-server-isnt-routing-properly

Any help on resolving this issue would be of great help, thank you for your help.

24 Mar
1 year ago

tareenmj left a reply on Does GET Data Have Higher Priority Than POST Data In Laravel 5.4?

If I have a form which has a method POST and also a route which POSTS, but I do supply a URL with GET data in my form, which takes priority? Let me elaborate: From my form I post two variables x=3 and y=4 but in my URL I give GET data like: x=1 and y=2. If I then print the data, will x=3 or 1?

tareenmj started a new conversation Does GET Data Have Higher Priority Than POST Data In Laravel 5.4?

So I am a beginner at Laravel and following a book (Codesmart which uses Laravel 5) whereas I am using 5.4. So I created a simple form like:

        {{ csrf_field() }}

        <input type="hidden" name="foo" value="bar" />
        <input type="hidden" name="baz" value="boo" />
        <input type="submit" value="send" />

and my routes web.php file looked like:

Route::get('post-form', function(){ return view('form');

});

Route::post('/', function(){ $data=Request::all(); var_dump($data); });

My output looked like: array(4) { ["_token"]=> string(40) "FNOgfFXulxabXbIEBxB3Jliq8buFgjCGrWgHdiuh" ["foo"]=> string(3) "bar" ["baz"]=> string(3) "boo" ["l"]=> string(4) "loki" }.

My book explicitely says that GET data has higher priority and the values of "foo" and "baz" should equal "get" but in my case obviously it's different. Any help would be greatly appreciated.

23 Mar
1 year ago

tareenmj left a reply on POST Causing Errors

@Cronix ohhh that makes more sense, so when I do the command $data=Request::all () it will also pass the token field to the variable data and that's why when I do var_dump ($data), the token is also included in the array? Is there any sort of function which would exclude the token and give me all of the submitted values??

Thanks guys for all your help!!

tareenmj left a reply on POST Causing Errors

@tykus Thanks! I think the url() was the problem and I am working locally. So now it works and I have no idea why (this is my web.php file):

tareenmj left a reply on POST Causing Errors

@tykus I placed the routes in my routes/web.php. I did loads of research but can't figure it out.

tareenmj left a reply on POST Causing Errors

I didn't have any url included in the view? Was I meant to include a url in my form.blade?

tareenmj started a new conversation POST Causing Errors

So I am a beginner to Laravel and I was expiremnting with POST and GET. So I attempted to create a simple form in my views directory called form.blade.php:

{{ csrf_field() }}

My routes file was like this:

Route::get('post-form', function(){ return view('form');

});

Route::post('/', function(){ $data= Request::all(); var_dump($data);

});

As soon as I attempt to submit the form, an error is thrown at me: MethodNotAllowedHttpException in RouteCollection.php line 233:

I do not understand why this is happening as my logic seems to be correct to me. Any help and solutions would be greatly appreciated. Thank you!

22 Mar
1 year ago

tareenmj left a reply on Two Models With Two Different Databases

I'm trying to create a table using Laravel, and also pull in data and enter data into an existing table on the same database. I felt for creating a table I would have to use migrations and then create a model whereas for an existing one I would have to just create a model. Yea apologies, I could have worded it better.

tareenmj started a new conversation Two Models With Two Different Databases

I am just a beginner at Laravel, so I probably do not know a lot. I created a migration and created a new table using Laravel, and also created a new model for that table so I could refer to it as App\Task and my table's name is tasks (it has one ID column, one body column, one created_at, and one updated_at column). I also wanted to edit and pull in information from another table I created on MySQL workbench in the same database. I created a new model called test and the table name was tests (it has only one id column and one description column) . Now using php artisan tinker, when I enter: App\test::get() it fetches all the records from the existing table. I also wanted to enter data into the table so I attempted this command in tinker: $entry=new App\test; and then $entry->description="Random Entry"; and finally when I entered: $entry; To my confusion, it displayed that entry had a description column, a created_at value and an updated_at entry. It won't let me save $entry into my test table either because of the additional column. Could someone please explain this and provide a solution?

Thanks for your help!