laravel-5,mass-assignment , Laravel 5 Modify Mass Assignment

Laravel 5 Modify Mass Assignment


Tag: laravel-5,mass-assignment

How I can change the fillable attribute of a model on the fly?

For example, I have User model with, protected $fillable = ['name', 'email', 'password']

When updating the user, I want to exclude 'email' from mass assignment so that the email is not changed on update.


Mass assignment doesn't mean all the field listed in fillable will be auto filled.

You still have control over what to save in the table.

So if you do:

$user = User::find(1);
$user->email = '[email protected]';

Only email will be saved in the example above while name and password remains the same


What is the best practice to implement update profile picture in PHP Laravel 5?

I'm trying to allow my user to update their profile photo and I'm wondering what is the best practice to implement something like that in Laravel. Here is my user profile picture. When they hover on it, they will have an option to update their photo. When the user click...

Laravel and Geocoding markers (nearby users) do not update correctly

I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map...

Laravel GET parameters that include dots cannot be checked

I'm trying to determine whether a parameter is in the URL or not. I use: $request->has('key'); And it's been working properly until now when I have to check wethere I have openid.ns parameter in the URL. If I remove the .(dot) everything works as expected, but: URL: And then...

Laravel 5 not storing checkbox value

We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value. We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a...

Change extends(layout) dynamically in laravel 5

I have been trying to change layout dynamically in laravel by just passing a variable in @extends('default1.master') to $var = default2 @extends('$var.master') possibly @extends($var.'.master') tried a lot but unable to find a solution all I get is error in my syntax or view not found....

Retrieving the Slug from URL for function (Laravel 5)

I'm making an App where a group is created by a user. This user can go to the group page (automated unique slug is created for the groups). My goal is for the member who created the group, to be able to make a invite code for that specific group....

How to register global variable for my Laravel application?

I have started with Laravel a few days ago, and today I just installed the vespakoen/menu that seems to be very nice, and probably will work for what I need it. Currently I have installed Laravel 5.1 on my system. The problem I currently have, is where to register my...

Sync element to a child on Laravel

My Shema database is User Table id login parent Sign Table id name user_id (Sign owner) Pivot table user_sign id user_id sign_id My User model contain public function signs() { return $this->belongsToMany('App\Sign', 'user_sign'); } public function parent(){ return $this->belongsTo('User', 'parent'); } public function children(){ return $this->hasMany('User', 'parent', 'user_id'); } And...

Laravel 5 form request validation returning forbidden error

I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php. My set up so far: routes.php: Route::post('clinic/{id}', array('as' => 'postUpdateAddress', 'uses' =>...

Laravel5: Access public variable in another class

I have a middleware file called LanguageMiddleware.php: ... class LanguageMiddleware { //ISO language codes: public $languages = ['en','es','fr','de','pt','pl','zh','ja']; ... LanguageMiddleware.php is in laravelProj/app/Http/Middleware/ Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages @foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang) <a class=\"setLang\" href=\"lang/en\">{{...

Laravel 5 confirmation error message display in wrong field

I would like to check if there is an error in my code I did not realize but why is my confirmation field's error message keep on displaying in the wrong filed? Suppose I have a password field and a password_confirmation field, but every time when user made a mistake...

Laravel 5 MethodNotAllowedHttpException

I am using a form with PATCH method and I have a button link(since i already have a submit button and using same form for both store and update) as <a class="btn btn-default" href="{{ URL::to( 'pages/edit/' . $vehicle -> id) }}">EDIT</a> And my route is Route::patch('/pages/edit/{id}', ['uses' => '[email protected]']); Controller...

Retreiving a single colum from a pivot table - Laravel 5

I am using a pivot table genre_user to relate user to genre. table contains the following fields id user_id genre_id Following are the model definitions User.php public function genres() { return $this->belongsToMany('App\Genre'); } Genre.php public function artists() { return $this->belongsToMany('App\User'); } I am getting the results as a collection when...

Deleting migrations results in an Exception

In my Application, when I run php artisan migrate:make create_location_user_table, then delete the generated file (doesn't matter if I delete the line created in vendor/composer/autoload_classmap.php, the php artisan migrate:refresh command throws an error: include(<path_to_project>/database/migrations/2015_06_21_105357_create_location_user_table.php): failed to open stream: No such file or directory After running commands to get rid of...

Only execute methods if session value laravel 5

I have a controller with alot of methods than should only be allowed to be executed if I have a certain value in my session. This is what I do at the moment: I made a private method that can either return the value 'yes' or 'no' Wich I call...

Laravel 5: Call method in class before the method indicated by the route

I'm sure there's a well documented way to do this in Laravel, I'm just missing it or not understanding what I'm reading. I have an application that uses a token for accessing part of the website, rather than a username or password. That token identifies the job, checks the status...

Laravel 5 pagination with trailing slash redirect to 301

I'm using Laravel 5 and notice that the pagination is adding a trailing slash before the ?page=# and with that, it always redirect to a 301 page. will do a 301 redirect to This is causing my pagination using ajax to slow down because it is having 2...

Laravel 5.1, Return response to user, then excute some code [closed]

The Story I am using NotificationPusher that uses GCM to send notification to user. It takes some time to connect to google server and wait for response. So, I don't want my user to wait until notification is sent, I want him to get the response (say that he successfully...

Laravel 5 - How to get Auth user ID in controller, retrieve user data and display that data in view

New to the Laravel 5 framework (and OOP), I want to create a view where a user can view/edit his own user profile when he's logged in. What would be the syntax to get Auth user ID in controller, retrieve user data (from DB) and display that data in the...

Get base_url using Jquery in Laravel

I am using laravel 5.0. I want to get base url of laravel page using jquery. I have tried the following function. function getBaseURL () { return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/"; } But this gives only http://localhost. I need my full...

Angular - Uncaught ReferenceError: angular is not defined

I'm trying to use a simple Angular function in my Laravel 5 project and I keep getting this error: angular is not defined I have tried to move angular.min.js to the top making it the first JS script on my index page but it still doesn't work. This is my...

Handling 500 Internal Server Error from DomDocument in Laravel 5

The library I wrote for Laravel uses DomDocument. I use this library under my Controller, and its namespace is app/Services/Verify/. The library gets initialized and used when I put it some inputs into a form. When the library fails, Laravel would fail the way it would - returning the following...

Mysql - Laravel - order by and rownum position not in sync in 2 queries

So I have a list of users, who receive votes, they are ordered by votes DESC, but then I have another query that gets their current position I.E. 1st place, 2nd place, 10th, place, etc. The problem is when people have the same number of votes, the position isn't in...

How to validate an input date from individual day, month, year input in Laravel 5

I have a user registration form which takes input birth day split in 3 different input fields i.e. day, month, year {!! Form::selectMonth('month', null) !!} {!! Form::selectRange('day', 1, 31, null) !!} {!! Form::selectYear('year', Carbon\Carbon::now()->year, (new Carbon\Carbon('100 years ago'))->year, null) !!} In the backend I have modified the Registrar.php/validator() to check...

Update enum column in Laravel migration using PostgreSQL

According to this answer, I have to run a raw query if I want to update an enum in MySQL. But with PostgreSQL, I can't use this query, and enum type for PostgreSQL in Laravel seems strange. Is there any way to update enum in a migration for postgreSQL ?...

Laravel 5.1 throws ReflectionException after upgrade from 5.0

I have recently upgraded Laravel to version 5.1 from 5.0, but whenever I send an API response to the server, it throws an exception like the following: ReflectionException in RouteDependencyResolverTrait.php line 57: Class App\Http\Requests\User\GetRequest does not exist Before upgrading everything was working fine. This is the autoload section of my...

laravel file uploading using json

I am using laravel 5. I have did the following code to post data using json to my controller. But I cannot make file uploading by this manner. e.preventDefault(); $.ajax({ type: 'POST', cache: false, dataType: 'JSON', url: 'tasks', data: $('#my_form').serialize(), success: function(data) { console.log(data); }, }); I have the following...

How to turn an s3 object string into something useful when using laravel 5.1 filesystem

I'm at a loss. I'm trying to display an object (image.jpg) I successfully have uploaded to my s3 bucket. I have made sure the file is set to public. I use the Storage::get(); method which the doc says "returns a string of the object". See here: The get method may...

Laravel validator vs requests

Hello, I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get. What is the difference between using a request file for validation...

Laravel method attributesToArray() not running on production

I'm deploying my application to my production environment and it's not working as expected. I've narrowed the issue down to one line inside this loop in my controller; foreach($temp_table_data as $a_payment) { //array_push($payments, $a_payment->payment); //big collection object array_push($payments, $a_payment->payment->first()->attributesToArray()); //smaller object } The error I get is call to a...

Physical delete a model which is enabled softdelete in laravel5?

I am using SoftDeletes for a model in Laravel5. But in some cases (Keeping history is not useful),I want to do physical delete (Removing row from table)instead of softDelete. class PaymentInvoices extends Model { use SoftDeletes; } Is there any method for forcing physical delete? ...

laravel 5.1 not seeing changes to Job file without VM restart

I have created a new Job in a laravel 5.1 app, running in Homestead VM. I've set it to be queued and have code in the handle method. The handle() method previous expected a param to be passed, but is no longer required and I've removed the param form the...

Laravel 5 Modify Mass Assignment

How I can change the fillable attribute of a model on the fly? For example, I have User model with, protected $fillable = ['name', 'email', 'password'] When updating the user, I want to exclude 'email' from mass assignment so that the email is not changed on update....

How can I Echoing Data After Checking For Existence in PHP Laravel 5?

I don't have anything store on my user phone field at the moment. <li><i class="md md-phone"></i> {{ $user->phone or 'No Phone' }} </li> So this line should print out No Phone. But instead it print out as blank. I'm confuse. What did I do wrong /forgot ? Is it because...

Redirect to Login page if ther user not logged in Laravel

I am using Laravel version 5. I have a route file for my project which contains plenty of lines. I need to put authentication like Redirect to login page if the user is not logged in. And I also want to prevent direct URL access if the user not logged...

Setting up a second Homestead Laravel app

I've been trying to set up a second Laravel 5 app on my local Homestead space. I have been following the instructions from the official documentation and from this blog. (Although I have had to use the specific ID of the provision in order to get the vagrant provision command...

Laravel - Guzzle not returning any data even though URL is correct

I am trying to return the JSON data from a third party API - I currently have in my controller: $client = new Client(); $request = $client ->get(''.Input::get('postcode')); $statusCode = $request->getStatusCode(); if ($statusCode >= 200 && $statusCode < 300) { $json = Response::json($request); // Returns JSON decoded array of...

Restrict laravel to open url that is not in route

I am Learning laravel now. Today I came across a problem that surprised me. I open this link in my browser: http://localhost/laravel/project/ch/resources/views/pages/blog.blade.php And I expect error 404. but it opens contains of this file. So, How to restrict laravel to do this. I want laravel to open only url mentioned...

Laravel: Best practice for inline PHP in a blade file

So I have the following blade file: confirmEmail.blade.php @extends('layouts.master') @section('title') {{ trans('tc.signUpConfirmTitle')}} @endsection @section('body') <div class="container"> <div class="row"> <div class="col-lg-4"> &nbsp; </div> <div class="col-lg-4"> <?php echo $_GET['emailToken']; $emailToken = isset($_GET['emailToken']) ? $_GET['emailToken'] : ""; $email = isset($_GET['email']) ? $_GET['email'] : ""; //database lookup: $user = User::where('email','=',$email)->first(); //this...

Laravel 5 : on success Validation Request function

In laravel 5, we can now use the Request classes for input validation like so : public function store(StoreItemRequest $request) { $item = Item::create($request->all()); return 'success'; } When the validation fails, I can get the errors thanks to the response function in the Request class : public function response(array $errors)...

Laravel 5.2 Job with delay fires instantly instead of waiting

I'm creating an application with the Laravel 5.2 framework. In my application there is a job that I want to fire 2 days after the event. This is the code where an instance of the right job is made and where I set the delay to the amount of seconds...

Laravel 5 making a route for a specific link

I have a link that goes to a address like http://localhost/pages/vehicles?show=61 Is it possible to make a route for that kind of link i tired below route but it does not work Route::get('/pages/vehicles?show={id}', ['middleware' => ['roles'], 'uses' => '[email protected]', 'roles' => ['Admin']]); ...

Laravel 5.0: Form::select() called twice Eloquent Accessor by select name

Blade template: {!! Form::model($category) !!} {!! Form::select('drinks_id', [...full list...]) !!} {!! Form::close() !!} 'drinks_id' called by Eloquent Accessor: public function getDrinksIdAttribute() { var_dump('get'); return 123; } When Form::select('drinks_id') execute, getDrinksIdAttribute() called twice and print string(3) "get" string(3) "get" from var_dump(). If I write this: {!! Form::model($category) !!} {!! var_dump($category->drinks_id) !!}...

PHP custom sort on an object array Laravel-5

I need to build a custom sort on an object array but i'm not sure where to start. I've seen the functions usort() etc but I can't see how i'd implement these functions for what I require. My application is returning the below object array. I need to order it...

Getting code from my forked repository

I made a fork from a repository called "chrisbjr/api-guard". the repository latest version is v2.2.2, and I made a release v2.2.3 from my fork. I have my own branch which is dev-fulluth, to get the code from my fork not from the main repo, composer has to contain the below...

Guzzle error 500

so i have a CURL request that looks like this (and it works): curl -X GET -H "Authorization: Token 1234567890" tried translating it into Laravel Guzzle into something like this: $client = new \GuzzleHttp\Client(['base_uri' => '']); $headers = ['Authorization' => 'Token 1234567890']; $response = $client->get($query_string, $headers); return $response; but...

How to add and make sure there's one space after every

and before

I am comparing string and displaying differences. These text string might have tags. Problematic situation is when two tags are not separated with a space, example: <p>Some random text</p> is compared to <p><strong>Some random</strong> text</p>. In this case diff algorithm thinks that 1st diff is <p>Some and <p><strong>Some and to...

Cannot get parameter value from url in main page

I searched a lot for the issue. But I couldn't find anything related to getting parameter value from get request in app.blade.php file. URL: http://localhost:8000/project/dashboard/1 I want to get this parameter value after user is signed in. Following is the code in AuthController. if ($this->auth->attempt($request->only('email', 'password'))) { return redirect()->route('dashboard', ['id'...

Cannot insert the value NULL into column 'user_id', table 'dbo.role_user'; column does not allow nulls

I am using Zizaco/Entrust in Laravel 5.0 to apply RBAC and i'm having the following error: Cannot insert the value NULL into column 'user_id', table 'dbo.role_user'; column does not allow nulls. INSERT fails. (SQL: insert into [role_user] ([role_id], [user_id]) values (2, )) I followed all the steps to implement Entrust...