Menu
  • HOME
  • TAGS

Using slugs in laravel 5?

laravel-5,slug

Yes, you can use slug in your route and generated url, for example, if you declare a route something like this: Route::get('users/{username}', '[email protected]')->where('profile', '[a-z]+'); Then in your controller, you may declare the method like this: public function profile($username) { $user = User::where('username', $username)->first(); } The username is your slug here...

Angular - Uncaught ReferenceError: angular is not defined

javascript,php,angularjs,laravel-5

I have seen this issue before. In my case it was due to the incorrect relative reference i was using. I am not an expert in this matter but i would recommend you to try with different combinations and see if it helps. Also see where the js folder is...

Trying to connect Ionic App to a Laravel API

angularjs,laravel,laravel-5,ionic-framework,ionic

Initially I couldn't get this solution to work, but it turns out I just had to create the temp folder. So to make this easy to use I dropped into .bashrc and open from my terminal in a separate Chrome instance with the web security disabled. .bashrc shortcut # Execute...

Retreiving a single colum from a pivot table - Laravel 5

php,laravel,eloquent,laravel-5

I think what will help you achieve this behavior is the lists() method. Try something like $user_genres = auth()->user()->genres()->lists('name','id'); If you are using Forms & HTML package you can just do {!! Form::select('genres',$user_genres,null) !!} And here is your dropdown More info here (scroll down to "Retrieving A List Of Column...

Laravel put foreach inside mail

php,laravel,laravel-5,sendmail,swiftmailer

Use foreach outside Mail() as below : $production_string = ''; foreach ($mand as $rij) { $production_string .= "Name : ".$rij->name; $production_string .= ", Quantity : ".$rij->qty; } Mail::send('emails.bestelling', array( 'mededeling' => $bestelcode, 'rekeningnummer' => '000/000000/00', 'naam' => $userNaam, 'totaal' => $totaal, 'producten' => $production_string } ), function($message) { $message->from('[email protected]'); $message->to('[email protected]',...

Can't install guzzlehttp for Laravel

laravel-5,guzzle

try, composer require "guzzlehttp/guzzle:~5.3" ...

Deleting migrations results in an Exception

php,laravel,laravel-5,composer-php,autoload

Go into your mysql database manually (PHPMyAdmin) and remove the migrations table. With the steps you've taken above and doing this should solve your issue

Laravel 5 form request validation returning forbidden error

php,validation,laravel,laravel-4,laravel-5

You are getting Forbidden Error because authorize() method of form request is returning false: The issue is this: $clinicId = $this->route('postUpdateAddress'); To access a route parameter value in Form Requests you could do this: $clinicId = \Route::input('id'); //to get the value of {id} so authorize() should look like this: public...

L5 Paypal Integration - Finding Controller method

laravel,laravel-5

Although laravel allows you to generate url's to actions. I researched what happened in the code. In the UrlGenerator class: /** * Get the URL to a controller action. * * @param string $action * @param mixed $parameters * @param bool $absolute * @return string * * @throws \InvalidArgumentException */...

What is the best practice to create a custom helper function in php Laravel 5?

php,laravel,laravel-5,view-helpers

Within your app/Http directory, create a helpers.php file and add your functions. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"]. Run composer dump-autoload That should do it. :)...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

Maximum function nesting level of '100' reached, aborting after upgrading to Laravel 5.1

php,laravel-5,homestead

Issue is caused by default xdebug.max_nesting_level which is 100. The workaround for now is to increase xdebug.max_nesting_level to a certain level say 200 or 300 or 400 I fixed mine by increasing xdebug.max_nesting_level to 120, by adding the line below to bootstrap/autoload.php in Laravel 5.1 ini_set('xdebug.max_nesting_level', 120); ......... define('LARAVEL_START', microtime(true));...

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

and before

php,laravel-5

(<del><p> is not valid markup as <del> is an inline element but <p> is a block-level elements, inline elements cannot contain block-level elements). Your underlying issue would be better solved with an XML-aware diffing algorithm rather than your current whitespace-sensitive text-only diff. However I am sensitive to the need for...

How can validate only a certain fields in php Laravel 5?

php,validation,laravel,laravel-5

It should be : $validator = Validator::make($input, [ 'phone' => 'max:20', 'email' => 'required|email|unique:users,email,'. $id , 'address' => 'max:255'] ); It thinks you are passing the first line as the data to check, and the second line as the rules for your validation. It doesn't find an email key so...

laravel file uploading using json

jquery,ajax,json,laravel,laravel-5

Use this as your code: e.preventDefault(); var mydata = new FormData($('#my_form')[0]); $.ajax({ type: 'POST', cache: false, dataType: 'JSON', url: 'tasks', data: mydata, processData: false, contentType: flase success: function(data) { console.log(data); }, }); Note that this doesn't work on some older browsers such as IE 9 or older so you might...

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

php,amazon-s3,laravel-5,file-conversion,flysystem

Okay, so I made things work, but I am in no way sure if this is the smartest way. But hey, it's a step of the way. Note this solution lets anyone, authenticated or not, access your s3 objects url. I haven't figured out how to control access yet. Useful...

How can I move file in php Laravel 5 ?

php,laravel,laravel-4,laravel-5

You're moving the file in the wrong direction. It should be $move = File::move($old_path, $new_path); ... in other words, the first argument should be the OLD file location, the second argument should be the NEW file location... you have it backwards. :) From the Laravel Docs Move A File To...

Laravel 5 View is loading from cache and new code not affecting

php,laravel,laravel-5,blade

I made a package (artisan command) for clearing views because it was really annoying to clear them manually. https://github.com/Kyslik/view-clear when installed just $ php artisan view:clear If you are using Laravel 5.1.* you dont need this package since it is part of Laravel base commands. Perhaps browser itself is doing...

Error while Eager loading a Eloquent model with multiple relationship in Laravel 5

php,laravel,eloquent,laravel-5,relationship

You are trying to get id from an null profile. Please check one of your results and see that inside relations property you have profile as null Please check first if profile is null and only after that get your field Good luck....

Laravel 5 How to Pass 2 Models to a Form

php,forms,laravel,model,laravel-5

In short you need to pass your view a instance of Vehicle with Client - I know you're trying to do that with the join but I'm guessing that isn't the right way to do it. I set up a clean install with Laravel and it appears to work when...

full text search with multiple text input

sql,laravel,input,full-text-search,laravel-5

UPDATED: Try $products = DB::table('products') ->whereRaw('MATCH(HEX,RGB) AGAINST(? IN BOOLEAN MODE)', array("$hex $rgb") ->get(); "$hex $rgb" - no FTS operators means $hex OR $rgb "+$hex +rgb" - means $hex AND $rgb Here is a SQLFiddle demo Further reading: Boolean Full-Text Searches ...

Merging collections

laravel,eloquent,laravel-5

Now, when using Product:: you'll get with an Eloquent Collection object which holds your results from using get or any other relationship. The nice thing here is that you can actually choose and customize your Collection, instead of using plain array or something else. Please read additional details here: http://laravel.com/docs/5.1/eloquent-collections#available-methods....

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

php,mysql,sql-order-by,laravel-5,rownum

I think you can order by two conditions such as ORDER BY vote_count DESC, user_id ASC. That is if I remember correctly.

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

javascript,php,jquery,laravel,laravel-5

I solved it by doing this HTML {!! Form::model($user, array('route' => array('user.update_profile_picture', $user->id ),'method' => 'PUT')) !!} <a class="pmop-edit" > <span id="file-upload" > <i class="md md-camera-alt"></i> <span class="hidden-xs">Update Profile Picture</span> </span> <div style='height: 0px;width: 0px; overflow:hidden;'> <input id="upfile" type="file" value="upload" onchange="sub(this)" /> </div> </a> {!! Form::hidden('$id', $user->id)!!} {!!...

File makeDirectory

laravel-5

You can do this by setting recursive option of File::makeDirectory method to true which will create all folders/sub folders in the path if they don't exists: File::makeDirectory($path=base_path("public/userfolder/{$data['username']}"), $mode = 0755, $recursive = true, $force = false);...

Laravel 5 : get route parameter in Controller 's constructor

laravel,laravel-5

You should be able to do something like this $id = Route::current()->getParameter('id'); ...

Laravel 5 getting input values that are arrays

php,laravel,input,laravel-5,laravel-form

The Request::get() method is implemented by Symfony\Component\HttpFoundation\Request which the Illuminate\Http\Request class extends. This method does not parse the string parameter passed using the dot notation as Laravel does. You should instead be using the Request::input which does: $adress = Request::input('representive.address_1'); As an alternative you can also use the Input facade...

Laravel 5 Modify Mass Assignment

laravel-5,mass-assignment

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]'; $user->save(); Only email will be saved in the example above while name and password remains...

Laravel GET parameters that include dots cannot be checked

php,laravel-5

To determine if the openid.ns value is present on the request, you can do it by: $request->has('openid_ns') ...

Physical delete a model which is enabled softdelete in laravel5?

php,mysql,laravel,laravel-5,soft-delete

Of course there is. Use forceDelete method instead of just delete. Keep in mind, forceDelete is only available if you use the SoftDeletes trait. Example $instance->delete() //This is a soft delete $instance->forceDelete() // This is a 'hard' delete More info here (scroll down to Permanently Deleting Models)...

Change extends(layout) dynamically in laravel 5

layout,laravel-5

in your view you can pass a variable with the view name like @extends('layout.'.$view) //or @extends($view.'.base') here $view is a variable which stored the view name from controller my controller looks following $view = 'base'; return view('someview', compact('view')); and if by any chance you are declaring this $var in the...

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

php,laravel,laravel-5

{{ $var or 'No Phone' }} === {{ isset($var)? $var : 'No Phone' }} Because $user->phone is defined you should use this: {{ $user->phone? $user->phone : 'No Phone' }} Or, you can go nice Laravel way and create your own directive for Blade templates and use it like this: @var($user->phone,...

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

php,laravel,eloquent,laravel-5,accessor

FormBuilder use object_get() helper function for get value from model: /** * Get the model value that should be assigned to the field. * * @param string $name * @return string */ protected function getModelValueAttribute($name) { if (is_object($this->model)) { return object_get($this->model, $this->transformKey($name)); } elseif (is_array($this->model)) { return array_get($this->model, $this->transformKey($name)); }...

Laravel method attributesToArray() not running on production

php,laravel,laravel-5

One of the tempTable models doesnt have a Payment and the attributesToArray() method is failing. Try this and see if it works. foreach($temp_table_data as $a_payment) { $payment = $a_payment->payment->first(); if(!is_null($payment)){ $payments[] = $payment->attributesToArray(); } } ...

Laravel validator vs requests

laravel,laravel-5,laravel-validation

1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate,...

Laravel5: Access public variable in another class

php,class,oop,laravel,laravel-5

That's simple php stuff. Set the attribute as static and access it with ::. class LanguageMiddleware { public static $languages = ['en','es','fr','de','pt','pl','zh','ja']; } @foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang) ... @endforeach You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and...

Getting code from my forked repository

git,laravel,repository,laravel-5,composer-php

Having a look at your repository in https://github.com/Yunishawash/api-guard it looks like it doesn't have a branch called dev-fullauth. Instead there is a branch dev-bugfix. But you must not name your branch including the dev- prefix. Rename your branch at github from dev-bugfix to bugfix and then your require section would...

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

php,laravel-5,rbac

Extra info: Entrust needs a userid to be able to assign a role to the user. When you create a user there is no userid cause a userid will be created when you create the user. So after creating the user you need to retrive the user first before you...

Laravel 5 : [Call to a member function getAction() on a non-object

laravel,laravel-5,laravel-routing

Seems obvious doesn't it? Get current route in a browser will return the currently visited route. In the terminal you do not such a request. Laravel will return null when asking what route is visited. You would have to check for the return value before calling getAction....

Laravel 5 - Sending group emails

php,laravel,laravel-5

Rather than using Laravel's built in Mail, I elected to use Mailgun's API (specifically batch sending) directly - mailgun/mailgun-php $mailgun = new Mailgun('API-KEY'); $recipientVariables = [ "[email protected]" => ['name' => 'Benny'], "[email protected]" => ['name' => 'James'] ]; $mailgun->sendMessage('demo.org', [ "from" => '[email protected]', "to" => '[email protected], [email protected]', "subject" => 'Cool Email',...

Creating an Eloquent Object with relation included

php,laravel,eloquent,laravel-5,foreign-key-relationship

You may try something like the following. At first save the parent model like this: $user = new \App\User; $user->first_name = $request->input('first_name'); // ... $user->save(); Then create and save the related model using something like this: $profile = new \App\Profile(['mobile_no' => $request->input('mobile')]); $user->profile()->save($profile); Also make sure you have created the...

Retrieving the Slug from URL for function (Laravel 5)

php,eloquent,laravel-5,blade,slug

Fixed it: Route: $router->post('invites/{slug}', ['as' => 'invite.create', 'uses' => '[email protected]']); My form: {!! Form::open(['route' => ['invite.create', $group->slug]]) !!} {!! Form::submit('Generate invite code', ['class' => 'btn btn-primary']) !!} {!! Form::close() !!} The function: public function createInviteCode($slug) { $group = Group::where('slug', $slug)->firstOrFail(); // ... } ...

Input::all() empty after FormData object passed

javascript,jquery,laravel,laravel-5,form-data

Your problem is that you are using a GET to send a request with enctype = multipart/form-data. When you use a native FormData object this is the format that you get by default. You can read how to send the form's data using the POST method and setting the enctype...

laravel 5.1 not seeing changes to Job file without VM restart

php,laravel,laravel-5,homestead

When running the queue worker as a daemon, you must tell the worker to restart after a code change. Since daemon queue workers are long-lived processes, they will not pick up changes in your code without being restarted. So, the simplest way to deploy an application using daemon queue workers...

Guzzle error 500

php,laravel-5,guzzle

get() takes options (which can contain headers) as a second parameter, not headers (docs). This should work: $client = new \GuzzleHttp\Client(['base_uri' => 'http://api.website.com']); $headers = ['Authorization' => 'Token 1234567890']; $response = $client->get( $query_string, [ "headers" => $headers // you can add more options here ] ); return $response; ...

Restrict laravel to open url that is not in route

php,laravel,routing,laravel-5,laravel-5.1

This is because you access your site from http://localhost. Every file and folder that is inside your root folder is accessible via the browser. So don't run your project from localhost but from a proper virtual host. For example make http://project.dev and use that to access your site <VirtualHost *:80>...

Getting NotFoundHttpException when accessing a image file in uploads directory in Laravel 5.1

php,.htaccess,laravel,wamp,laravel-5

You cannot access directories and files that are above the document root, that is public. You need to move your uploads directory to the public directory.

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

php,android,laravel,android-gcm,laravel-5

You may use queue. When user comment post, add event to queue. Queue is parsed by cron (using Laravel's command).

Setting up a second Homestead Laravel app

laravel,laravel-5,homestead

The problem was in your homestead.yaml file. folders: - map: C:\Users\Lisa\Documents\Homestead\larapipeline to: /home/vagrant/Code/larapipelin - map: C:\Users\Lisa\Documents\Homestead\tinkertower to: /home/vagrant/Code/tinkertower sites: - map: homestead.app to: /home/vagrant/Code/larapipeline/public - map: tinkertower.app to: /home/vagrant/code/tinkertower/public Don't forget to edit your hosts file. Now run vagrant up --provision, or vagrant reload --provision. Edit: Fixed case sensitivity issue...

How can I use Elixir + Vueify?

javascript,laravel,laravel-5,vue.js

Install sudo npm install laravel-elixir-browserify vue vueify --save In your gulpfile.js add the following: var elixir = require('laravel-elixir'); var vueify = require('laravel-elixir-browserify').init("vueify"); elixir(function(mix) { // resources/assets/js/main.js mix.vueify('main.js', {insertGlobals: true, transform: "vueify", output: "public/js"}); }); Be Happy =D Laravel Elixir Browserify Extension Doc Click Here...

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

javascript,google-maps-api-3,laravel-5

It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing $.ajax({ type: "POST", url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(), async: false }); to $.ajax({ type: "POST", url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(), success: function(data, textStatus, jqXHR) { // request succeeded // data...

Laravel 5 making a route for a specific link

laravel,laravel-5,laravel-routing

I had a similar problem trying to send a form directly to a route (using something like /pages/vehicles/61) but it seems to be imposible (question here). If you don't have a specific route for all vehicles (/pages/vehicles doesn't show a list of vehicles) you can do something like: Route::get('pages/vehicles','[email protected]'); And...

Eloquent Query always returns null for parent table using oneToOne relationship

php,laravel,eloquent,laravel-5,one-to-one

You receive null for because your relation definition is wrong. Your profile model should be public function user() { return $this->belongsTo('App\User','user_id'); } The error is because you are trying to get the user object from a collection. Since you have used get() to retrieve data you are receiving a collection...

Get base_url using Jquery in Laravel

jquery,laravel,laravel-5

Do you mean you want the base url of your laravel app available anywhere your javascript? You can include this in your template.blade.php: <script type="text/javascript"> var APP_URL = {!! json_encode(url('/')) !!}; </script> And than access that var anywhere in your javascript: console.log(APP_URL); ...

Laravel 5.1 throws ReflectionException after upgrade from 5.0

laravel,laravel-5

OK, I found the solution. I noticed that if in GetRequest class I swap use App\Http\Requests\Request; with use Request; then the GetRequest class is found and the ReflectionException is not thrown anymore. So the problem is not in the App\Http\Requests\User\GetRequest class but in the abstract class App\Http\Requests\Request. After looking at...

Nested queries, multiple tables in Laravel

laravel,laravel-5

For more complex queries and especially if you already built your sql query I recommend using the DB::statement function of laravel instead of eloquent. DB::statement(' SELECT * FROM creatives WHERE creative_id IN ( SELECT creative_id FROM term_relationships WHERE term_id IN (1, 2, 3) GROUP BY creative_id HAVING COUNT(*) = 3...

Laravel 5.2 Job with delay fires instantly instead of waiting

php,laravel,laravel-5,jobs

The issue ended up being the queue driver (in config/queue.php) was set to 'synchronous'.

PHP custom sort on an object array Laravel-5

php,arrays,laravel-5

You can try something like this public function index() { $bookingsDate = BookingDate::all() // Your actual collection $this->sortCollection($bookingDate); } public function sortCollection(\Collection &$bookingDate) { $bookingDate->sortBy(function($date) { $slots = [ 'Afternoon' => 1, 'Morning' => 2, 'All day' => 3, ]; $slot = $slots[$date['slot']]; return $slot; }); } The sortBy method...

Laravel query builder 'where' method is broken

php,mysql,laravel,laravel-5

As mentioned in the comments of your question, nothing is broken, running ->toSql() will show the query before any values are bound to it. If you need to see the values that are bound to the query you can use DB::listen(): DB::listen(function($sql, $bindings, $time) { var_dump($sql); // this is the...

Laravel 5 MethodNotAllowedHttpException

php,laravel,laravel-5,laravel-routing

Your <a> link will trigger a GET request, not a PATCH request. You can use JS to have it trigger a PATCH request, or use a <button> or <input type="submit"> to issue one.

Share value from database in all view in laravel 5

laravel-5

Info: This assumes your settings table structure is as following: ---------------------- | id | key | value | ---------------------- | 1 | title | foo | | 2 | asd | bar | | 3 | qqq | zzz | ---------------------- Steps Step 1: Put the following newCollection method into App\Setting...

Why is ::class appended to PHP class in Laravel 5.1

php,namespaces,laravel-5

PHP Documentation on ::class The feature has been introduced with version 5.5, which is now required by Laravel 5.1 The magic ::class property holds the FQN (fully qualified name) of the class. The advantages of it mostly comes with a good IDE. Some are: Less typos Easier Refactoring Auto-Completion Click...

How to change User Table in Laravel?

php,mysql,authentication,laravel,laravel-5

Go to app\Services\Registrar.php file, and in validator() function. public function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|confirmed|min:6', ]); } Change 'email' => 'required|email|max:255|unique:YOUR_TABLE_NAME', I believe this will solve your problem....

Laravel 5 confirmation error message display in wrong field

laravel,laravel-5,laravel-validation

because you have defined confirmed rule for your password field, all the errors related to password_confirmation will also be shown in password field.

Laravel Seeding: date manipulation not working

php,database,postgresql,laravel-5,php-carbon

It's because you are manipulating the same date object. If you need to manipulate a date and return as a new object preserving the current object use copy method before manipulating. Else it will return a reference to the same object you are manipulating. Change this line $nowDt->addMinutes($faker->numberBetween(35,45)); to $nowDt->copy()->addMinutes($faker->numberBetween(35,45));...

Only execute methods if session value laravel 5

php,laravel,laravel-5

Of course there is a better way. You are looking for a Middleware. First, create one: php artisan make:middleware SessionMiddleware Edit the file you just created: public function handle($request, Closure $next) { if (SESSION_KEY_IS_NOT_OK) { abort(403); } return $next($request); } Register it by editing your app/Http/Kernel.php file protected $routeMiddleware =...

Redirect to Login page if ther user not logged in Laravel

laravel,laravel-5,laravel-routing

You can put as many routes in a Group as you like to Route::group(array('before' => 'auth'), function(){ Route::get('/', '[email protected]'); Route::post('store', '[email protected]'); Route::get('show', '[email protected]'); // ... }); If you really need to protect all your routes, you could add public function __construct() { $this->middleware('auth'); } To your main controller class, Http/Controllers/Controller...

Laravel 5.1 AWS S3 Flysytem: AWS HTTP error: cURL error 6: Couldn't resolve host name

curl,file-upload,amazon-s3,laravel-5,host

Typical. Realized what was wrong after reading this article by Paul Robinson. I had set my s3 region to be Frankfurt. While my region sure enough is Frankfurt, I needed to refer to it as eu-central-1 as my s3 region in config/filesystems.php. After that I could go on to fix...

Laravel 5 form submit creates an error MethodNotAllowedHttpException

php,forms,controller,routes,laravel-5

Can you change this: Route::post('profile/edit', array( 'as' => 'admin.profile.update', 'uses' => '[email protected]' )); To this: Route::patch('profile/edit', array( 'as' => 'admin.profile.update', 'uses' => '[email protected]' )); I think your form action may need a matching route verb http://laravel.com/docs/5.1/routing#basic-routing For the second issue: Column not found: 1054 Unknown column '_method' in 'field list'...

Automaticlly attach to pivot table in Laravel 5

php,eloquent,pivot,relational-database,laravel-5

This should work, make sure you implement validation, ect. public function store(Request $request) { $group = Group::create([ // <-- if names are unique. if not, then create is fine 'name' => $request->get('name') ]); auth()->user()->groups()->attach([$group->id]); return view('your.view'); } Also make sure to add: use App\Group; ...

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

php,laravel,laravel-4,laravel-5,guzzle

What you are seeing is the raw response back from Guzzle and it needs to be formatted. A simple way is $response->getBody();. Think of this like a collection in Laravel. When you get the data back, it is in a collection with a bunch of extra data that may be...

Laravel: Best practice for inline PHP in a blade file

php,laravel,laravel-5,blade

Is using raw PHP like this defeating the whole purpose? Exactly ! MVC are made so that there will be different layers of different type of job Model, View and Controller here in your case you are combining the job of controller into a view and hence diminishing the role...

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

php,laravel-5

You try to display users, but you only have one user (the one that is logged in). Also you can simplify it a bit by just using Auth facade and not doing an other database call to get the same user. Controller: public function profile() { $user = Auth::user(); return...

Class 'User' not found - Laravel 5.1 [php artisan db:seed]

php,laravel-5

In your DatabaseSeeder in the root namespace you call the Class User. It therefor tries to load the class User. The definition of your class User is however in namespace App. You should therefor use either App\User in your DatabaseSeeder or add at the top of the file use App\User;...

laravel 5 ->getRealPath() doenst show correct value

php,laravel,laravel-5,intervention

Chances are your account's root is /data/sites/web/christophvhbe, and that getRealPath is entirely accurate (what you see in FTP is likely chrooted). As a result, your $imagePath is actually the problem. $imagePath = '/data/sites/web/christophvhbe/images/producten/'. $fileName; Or, better yet, use Laravel's base_path and/or public_path helpers so if you ever change hosting it...

FatalErrorException: Call to a member function count() on a non-object

php,database,random,laravel-5,unique

The error you're seeing is telling you that you're trying to call a method on a value which is not an object. Most likely in your code you're returning null as the where in your query didn't return anything results. You can always see what you're returning in Laravel queries...

Unable to override automatic model find method calls since upgrading to Laravel 5.1

laravel,laravel-5

Ok here it goes: short version: Model binding does not use find. longer version: /** * Register a model binder for a wildcard. * * @param string $key * @param string $class * @param \Closure|null $callback * @return void * * @throws NotFoundHttpException */ public function model($key, $class, Closure $callback...

Add DropzoneJS for file upload with Laravel 5

php,laravel,laravel-5,dropzone.js

Well I tried dropzone.js and it was was blazing fast and everything worked fine. And after looking at your code, I think I figured out your problem: On your route.php you have this: Route::post('/upload', function(){ $the_new_product->name = Input::get('name'); $the_new_product_picture = Input::file('file'); return dd($the_new_product_picture); // I get Null as respons });...

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

php,laravel,laravel-5,laravel-middleware

Middleware might be an option. Alternatively could you do this in the constructor of your BaseController? E.g. class BaseController extends Controller { public function __construct() { //if token in query string //load Job and check status Vs requested URL //redirect to correct URL } } ...

Cannot get parameter value from url in main page

laravel,laravel-5

You can do: Route::getCurrentRoute()->getParameter('id') See Illuminate\Routing\Route.php /** * Get a given parameter from the route. * * @param string $name * @param mixed $default * @return string|object */ public function getParameter($name, $default = null) { return $this->parameter($name, $default); } ...

Laravel 5 : on success Validation Request function

laravel-5,laravel-validation

Yeah, I found validate method in ValidateWhenResolvedTrait which you could override in your form request class; public function validate(){ $instance = $this->getValidatorInstance(); if($this->passesAuthorization()){ $this->failedAuthorization(); }elseif(!$instance->passes()){ $this->failedValidation($instance); }elseif( $instance->passes()){ if($this->ajax()) throw new HttpResponseException(response()->json(['success' => true])); } } ...

Laravel route model binding for just one route

php,laravel,laravel-5

Yes, you can do it easily only by changing the parameter name in your route that is being used for model binding, for example, why not use $item (or something like that) in the routes for which you need model binding so you can bind the model to routes which...

Update enum column in Laravel migration using PostgreSQL

postgresql,laravel,laravel-5,laravel-migrations

Laravel use constraint on character varying for enum. Assuming there is a table mytable with an enum column status, we have to drop the constraint (named tablename_columnname_check) then add it in a migration like this: DB::transaction(function () { DB::statement('ALTER TABLE mytable DROP CONSTRAINT mytable_status_check;'); DB::statement('ALTER TABLE mytable ADD CONSTRAINT mytable_status_check...

Laravel Eloquent how to return one to many to many collection

php,eloquent,laravel-5

The "has many through" relation provides a convenient short-cut for accessing distant relations via an intermediate relation. class User extends Model implements AuthenticatableContract, CanResetPasswordContract {{ ... public function galleries() { return $this->hasMany('App\Gallery'); } public function votes() { return $this->hasManyThrough('App\GalleryVote', 'App\Gallery'); } } Now $user->votes will return all votes for that...

Handling 500 Internal Server Error from DomDocument in Laravel 5

php,laravel,exception-handling,laravel-5

You could handle this in Laravel app/Exceptions/Hnadler.php NB: I have looked in the option of using DOMException handler which is available in PHP, however the error message you are getting in not really and exception by an I/O Warning. This what PHP native DomException looks like: /** * DOM operations...

Sync element to a child on Laravel

php,mysql,laravel,eloquent,laravel-5

As far as syncing/attaching you can use this sytanx $user->roles()->sync([1, 2, 3]); As given in Laravel Docs You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally. public function share(Request $request) { $userId = $request->input('user_id');...

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

php,date,laravel-5

Laravel using the strtotime and checkdate functions to validate a date. How the validateDate function of Laravel works? An example: strtotime('30-2-2015'); // returns a timestamp checkdate(2, 30, 2015); // returns false // laravel raises an error Therefore, the value of $data['date_of_birth'] should be a string in a particular format. public...

Laravel 5 pagination with trailing slash redirect to 301

php,laravel,redirect,pagination,laravel-5

If you look in your app/public/.htaccess file you will see this line: # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] By removing it you will disable trailing slash redirect....

Laravel 5 not storing checkbox value

php,laravel,checkbox,laravel-5

Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method. //File: User.php protected $fillable = ['optin']; ...

Laravel 5.1 View not found

php,laravel,laravel-5,blade,homestead

Turns out I had spelled blade incorrectly, took a second pair of eyes to actually notice it though. [email protected]:~/Development/laravel$ ls resources/views/crud/booking/ crud.balde.php index.balde.php Was definitely a lesson to always double check the small things when debugging. Thanks for the help....