#php json encode boolean
Explore tagged Tumblr posts
airman7com · 5 years ago
Text
PHP json encode - Konversi Array Ke JSON, Objek Ke JSON
PHP json encode – Konversi Array Ke JSON, Objek Ke JSON
Fungsi fungsi PHP json_encode () digunakan untuk mengubah array atau objek PHP menjadi JSON. PHP memiliki beberapa fungsi pre-built untuk menangani JSON.
Dalam tutorial ini, kita akan belajar bagaimana mengkonversi objek PHP ke JSON, mengkonversi PHP String ke JSON, PHP Array To JSON, mendapatkan data dari array JSON di php convert Multidimensional PHP Array ke JSON dengan definisi, sintaksis,…
View On WordPress
0 notes
longventure · 3 years ago
Text
Php json decode as object
Tumblr media
#Php json decode as object how to#
Let’s take the first example, here we will convert the JSON string to PHP array using the json_decode() function. Reviver method object can be passed in JSON.parse() to return a modified object of JSON in case of custom logic requires to add and return the different.
options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR.
#Php json decode as object how to#
Let’s see how to do it in practice with a few examples. There exist specific built-in functions that allow encoding and decoding JSON data. The data structures of JSON are identical to PHP arrays. Follow the steps and you’ll manage to meet your goal easily. Chapter 2 JSON encoding Creating a JSON object with PHP is simple: You just need to use the jsonencode () function. In this snippet, you can find a step-by-step guide on how to create and parse JSON data with PHP. depth: It states the recursion depth specified by user. Decode a JSON object received by your PHP script.If it is true then objects returned will be converted into associative arrays. Normally, jsondecode() will return an object of stdClass if the top level item in the JSON object is a dictionary or an indexed array if the JSON object. It only works with UTF-8 encoded strings. json: It holds the JSON string which need to be decode.The syntax of JSON decode function is:- json_decode(string, assoc, depth=500, options) Parameters of json_decode() function PHP: json_decode() | How to decode json to array in PHPĭefination:- The PHP json_decode() function, which is used to decode or convert a JSON object to a PHP object. An optional Assoc boolean to instruct whether to bypass conversion to an object and to produce an associative array. The decode function has the following parameters. It basically accepts three parameters, but you will usually only need the first one, i.e. Now jsondecode() on the other hand, has a completely different goal, which is to only attempt to convert a JSON string to a PHP object or array. will decode the json string as array For some reason I’m able to extract the json string as array but when I try it to do it as object it breaks. Like, convert JSON string to array PHP, convert JSON string to multidimensional array PHP and JSON decode and access object value PHP. You can also turn your own data into a well-formatted JSON string in PHP with the help of the jsonencode () function. Be wary that associative arrays in PHP can be a 'list' or 'object' when converted to/from JSON, depending on the keys (of absence of them). When decoding that string with jsondecode, 10,000 arrays (objects) is created in memory and then the result is returned. In this tutorial, we will take examples using the json_decode() function. JSON can be decoded to PHP arrays by using the associative true option. Efficient, easy-to-use, and fast PHP JSON stream parser - GitHub - halaxa/json-machine: Efficient, easy-to-use, and fast PHP JSON stream parser. PHP JSON decode In this tutorial, we will discuss about php json_decode() function syntax, defination, parameters with examples.
Tumblr media
0 notes
mbaljeetsingh · 8 years ago
Text
An Introduction to Laravel Authorization Gates
Laravel Gate has an elegant mechanism to ensure users are authorized to perform actions on resources.
Before version 5.1, developers used ACL packages such as Entrust or Sentinel along with middlewares for authorization. The problem with this approach is the permissions you attach to users are just flags; they don’t encode the complex logic of the permission for some use cases. We have to write the actual access logic within controllers.
Gate avoids some drawbacks of using just these mentioned packages:
Opinionated use case: Gate doesn’t define how you implement your models; it is up to you. This gives you the freedom to write all the complex specs your use case has however you like. You can even use ACL packages with Laravel Gate. Defining logic(policy): Using Gate we can decouple access logic from business logic, which helps remove the clutter from controllers.
A Usage Example
In this post, we’ll make a toy posts app to show how Gate gives you liberty and decoupling. The web app will have two user roles (authors and editors) with the following permissions:
Authors can create a post.
Authors can update their posts.
Editors can update any post.
Editors can publish posts.
Create a New Laravel Project
First, create a new Laravel 5.4 application.
laravel new blog
If you don’t have Laravel Installer, use composer create-project.
composer create-project --prefer-dist laravel/laravel blog
Basic Config
Update the .env file and give Laravel access to a database you’ve created.
... APP_URL=http://localhost:8000 ... DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dbname DB_USERNAME=dbuser DB_PASSWORD=yoursecretdbuserpassword ...
Database
Now, let’s create a Post model. Using -m and -c arguments we can create a migration and a controller for posts.
php artisan make:model Post -m -c
Next, update posts migration and add the following fields.
Open the posts migration file and add the following to up method:
Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('slug')->unique(); $table->text('body'); $table->boolean('published')->default(false); $table->unsignedInteger('user_id'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); });
We need to add a couple of other tables: roles and user_roles pivot table. We’re going to put the permissions inside the roles table like Sentinel does.
php artisan make:model Role -m
Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('slug')->unique(); $table->jsonb('permissions')->default('{}'); // jsonb deletes duplicates $table->timestamps(); });
And, lastly, role_users pivot table.
php artisan make:migration create_role_users_table
Schema::create('role_users', function (Blueprint $table) { $table->unsignedInteger('user_id'); $table->unsignedInteger('role_id'); $table->timestamps(); $table->unique(['user_id','role_id']); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); }); ...
Seeding the Database
To wrap up our database initialization, we’ll make seeds for roles.
php artisan make:seeder RolesSeeder
use Illuminate\Database\Seeder; use App\Role; class RolesSeeder extends Seeder { public function run() { $author = Role::create([ 'name' => 'Author', 'slug' => 'author', 'permissions' => [ 'create-post' => true, ] ]); $editor = Role::create([ 'name' => 'Editor', 'slug' => 'editor', 'permissions' => [ 'update-post' => true, 'publish-post' => true, ] ]); } }
Don’t forget to call RolesSeeder from DatabaseSeeder.
$this->call(\RolesSeeder::class);
User and Role Models
If we execute the seed command, it will fail because we haven’t set our models yet. Let’s add fillable fields to app/Role model, and tell our model permissions is a JSON type field. We also need to create relationships between app/Role and app/User models.
class Role extends Model { protected $fillable = [ 'name', 'slug', 'permissions', ]; protected $casts = [ 'permissions' => 'array', ]; public function users() { return $this->belongsToMany(User::class, 'role_users'); } public function hasAccess(array $permissions) : bool { foreach ($permissions as $permission) { if ($this->hasPermission($permission)) return true; } return false; } private function hasPermission(string $permission) : bool { return $this->permissions[$permission] ?? false; } }
class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; public function roles() { return $this->belongsToMany(Role::class, 'role_users'); } /** * Checks if User has access to $permissions. */ public function hasAccess(array $permissions) : bool { // check if the permission is available in any role foreach ($this->roles as $role) { if($role->hasAccess($permissions)) { return true; } } return false; } /** * Checks if the user belongs to role. */ public function inRole(string $roleSlug) { return $this->roles()->where('slug', $roleSlug)->count() == 1; } }
Now we can safely migrate and seed our database.
php artisan migrate --seed
Auth
Laravel provides a quick way to create routes and views for a simple authentication system using the following command:
php artisan make:auth
It will make controllers, views, and routes for us but we need to modify the registration to add the user role.
Registration
Let’s make roles available to the register view first. In Controllers/Auth/RegisterController.php override the showRegistrationForm method.
Use App/Role; ... public function showRegistrationForm() { $roles = Role::orderBy('name')->pluck('name', 'id'); return view('auth.register', compact('roles')); }
Edit resources/views/auth/register.blade.php and add a select input.
... <div class="form-group"> <label for="role" class="col-md-4 control-label">User role</label> <div class="col-md-6"> <select id="role" class="form-control" name="role" required> @foreach($roles as $id => $role) <option value=""></option> @endforeach </select> @if ($errors->has('role')) <span class="help-block"> <strong></strong> </span> @endif </div> </div> ...
Don’t forget to validate the new field we’ve added. Update validator method in RegisterController.
... protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', 'role' => 'required|exists:roles,id', // validating role ]); } ...
Override the create method in the controller (the method is inherited from RegistersUsers trait) and attach the role to the registered user.
... protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); $user->roles()->attach($data['role']); return $user; } ...
Change redirection link in RegisterController and in LoginController as well.
... protected $redirectTo = '/'; ...
Run the Application
If you run a server using php artisan serve command you’ll be able to create a user and attach a role to it from the browser. Visit /register and create a new user.
Define policies
Here we will define access policies to protect our actions. Update app/Providers/AuthServiceProvider.php to include the app’s policies.
use App\Post; ... public function boot() { $this->registerPolicies(); $this->registerPostPolicies(); } public function registerPostPolicies() { Gate::define('create-post', function ($user) { return $user->hasAccess(['create-post']); }); Gate::define('update-post', function ($user, Post $post) { return $user->hasAccess(['update-post']) or $user->id == $post->user_id; }); Gate::define('publish-post', function ($user) { return $user->hasAccess(['publish-post']); }); Gate::define('see-all-drafts', function ($user) { return $user->inRole('editor'); }); }
Routes
Let’s define our routes now; update routes/web.php with all our app’s routes.
Auth::routes(); Route::get('/', 'PostController@index'); Route::get('/posts', 'PostController@index')->name('list_posts'); Route::group(['prefix' => 'posts'], function () { Route::get('/drafts', 'PostController@drafts') ->name('list_drafts') ->middleware('auth'); Route::get('/show/{id}', 'PostController@show') ->name('show_post'); Route::get('/create', 'PostController@create') ->name('create_post') ->middleware('can:create-post'); Route::post('/create', 'PostController@store') ->name('store_post') ->middleware('can:create-post'); Route::get('/edit/{post}', 'PostController@edit') ->name('edit_post') ->middleware('can:update-post,post'); Route::post('/edit/{post}', 'PostController@update') ->name('update_post') ->middleware('can:update-post,post'); // using get to simplify Route::get('/publish/{post}', 'PostController@publish') ->name('publish_post') ->middleware('can:publish-post'); });
Posts
Let’s get busy with our posts, shall we?
Post model
First, we define our fillable fields, then add Eloquent relationships.
... class Post extends Model { protected $fillable = [ 'title', 'slug', 'body', 'user_id', ]; public function owner() { return $this->belongsTo(User::class); } public function scopePublished($query) { return $query->where('published', true); } public function scopeUnpublished($query) { return $query->where('published', false); } }
Posts Controller
We’ve already created a controller, now let’s make it useful.
List posts
Add index method to list all published posts in PostController.php.
use App\Post; ... public function index() { $posts = Post::published()->paginate(); return view('posts.index', compact('posts')); } ...
Next, edit resources/views/home.blade.php and rename it to resources/views/posts/index.blade.php.
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Posts @can('create-post') <a class="pull-right btn btn-sm btn-primary" href="">New</a> @endcan </div> <div class="panel-body"> <div class="row"> @foreach($posts as $post) <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <div class="caption"> <h3><a href=""></a></h3> <p></p> @can('update-post', $post) <p> <a href="" class="btn btn-sm btn-default" role="button">Edit</a> </p> @endcan </div> </div> </div> @endforeach </div> </div> </div> </div> </div> </div> @endsection
If we access the posts page as guests we won’t see the new button; only authors will be allowed to see it and access the page.
Create Posts
Let’s make a create post page. Add the following method to PostController.
... public function create() { return view('posts.create'); } ...
Create a view file and name it posts\create.blade.php.
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">New Post</div> <div class="panel-body"> <form class="form-horizontal" role="form" method="POST" action=""> <div class="form-group"> <label for="title" class="col-md-4 control-label">Title</label> <div class="col-md-6"> <input id="title" type="text" class="form-control" name="title" value="" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong></strong> </span> @endif </div> </div> <div class="form-group"> <label for="body" class="col-md-4 control-label">Body</label> <div class="col-md-6"> <textarea name="body" id="body" cols="30" rows="10" class="form-control" required></textarea> @if ($errors->has('body')) <span class="help-block"> <strong></strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Create </button> <a href="" class="btn btn-primary"> Cancel </a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Store Post
Next, we will make store method.
use App\Http\Requests\StorePost as StorePostRequest; use Auth; ... public function store(StorePostRequest $request) { $data = $request->only('title', 'body'); $data['slug'] = str_slug($data['title']); $data['user_id'] = Auth::user()->id; $post = Post::create($data); return redirect()->route('edit_post', ['id' => $post->id]); } ...
We need to make a StorePost request to validate the form data before storing posts. It’s simple; execute the following Artisan command.
php artisan make:request StorePost
Edit app/Http/Requests/StorePost.php and provide the validation we need in rules method. authorize method should always return true because we’re using Gate middlewares to do the actual access authorization.
public function authorize() { return true; // gate will be responsible for access } public function rules() { return [ 'title' => 'required|unique:posts', 'body' => 'required', ]; }
Drafts
We only want authors to be able to create posts, but these won’t be accessible to the public until the editors publish them. Thus, we will make a page for drafts or unpublished posts which will be only accessible by authenticated users.
To show drafts, add the drafts method to PostController.
use Gate; ... public function drafts() { $postsQuery = Post::unpublished(); if(Gate::denies('see-all-drafts')) { $postsQuery = $postsQuery->where('user_id', Auth::user()->id); } $posts = $postsQuery->paginate(); return view('posts.drafts', compact('posts')); } ...
Create the posts/drafts.blade.php view.
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> Drafts <a class="btn btn-sm btn-default pull-right" href="">Return</a> </div> <div class="panel-body"> <div class="row"> @foreach($posts as $post) <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <div class="caption"> <h3><a href=""></a></h3> <p></p> <p> @can('publish-post') <a href="" class="btn btn-sm btn-default" role="button">Publish</a> @endcan <a href="" class="btn btn-default" role="button">Edit</a> </p> </div> </div> </div> @endforeach </div> </div> </div> </div> </div> </div> @endsection
We need to make a link to access the drafts page. In layouts/app.blade.php, modify the dropdown menu and add a link to drafts page.
... <ul class="dropdown-menu" role="menu"> <li> <a href="">Drafts</a> ...
Edit Posts
Let’s make it possible to edit drafts and published posts. Add the following methods to PostController.
use App\Http\Requests\UpdaPost as UpdatePostRequest; ... public function edit(Post $post) { return view('posts.edit', compact('post')); } public function update(Post $post, UpdatePostRequest $request) { $data = $request->only('title', 'body'); $data['slug'] = str_slug($data['title']); $post->fill($data)->save(); return back(); }
We also need to create a new FormRequest. We have to make post titles unique, but allow them to have the same title on update. We use Laravel Rule for this.
Note the Post model will be accessible from the Request object because we have bound the id from the route to Post model. Check the official docs for more details.
php artisan make:request UpdatePost
use Illuminate\Validation\Rule; ... public function authorize() { return true; } public function rules() { $id = $this->route('post')->id; return [ 'title' => [ 'required', Rule::unique('posts')->where('id', '<>', $id), ], 'body' => 'required', ]; }
Create posts/edit.blade.php view
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Update Post</div> <div class="panel-body"> <form class="form-horizontal" role="form" method="POST" action=""> <div class="form-group"> <label for="title" class="col-md-4 control-label">Title</label> <div class="col-md-6"> <input id="title" type="text" class="form-control" name="title" value="" required autofocus> @if ($errors->has('title')) <span class="help-block"> <strong></strong> </span> @endif </div> </div> <div class="form-group"> <label for="body" class="col-md-4 control-label">Body</label> <div class="col-md-6"> <textarea name="body" id="body" cols="30" rows="10" class="form-control" required></textarea> @if ($errors->has('body')) <span class="help-block"> <strong></strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Update </button> @can('publish-post') <a href="" class="btn btn-primary"> Publish </a> @endcan <a href="" class="btn btn-primary"> Cancel </a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Publish Drafts
For the sake of simplicity, we will publish posts by visiting a get entry point. Using post with a form would be best. Add publish to PostController.
... public function publish(Post $post) { $post->published = true; $post->save(); return back(); } ...
Show Post
Let’s make posts available for publishing now. Add show to PostController.
... public function show($id) { $post = Post::published()->findOrFail($id); return view('posts.show', compact('post')); }
And the view, of course, is posts/show.blade.php.
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"> <a class="btn btn-sm btn-default pull-right" href="">Return</a> </div> <div class="panel-body"> </div> </div> </div> </div> </div> @endsection
404
To have a clean appearance when a user tries to visit a nonexisting page, we need to make a 404 page. We need to create a new Blade file errors/404.blade.php and allow the user to go back to a proper page.
<html> <body> <h1>404</h1> <a href="/">Back</a> </body> </html>
Conclusion
Our dummy application allows every user type to perform exactly the actions he has permission to. We’ve achieved that easily without using any third party packages. Thanks to this approach made possible by new Laravel releases, we don’t have to inherit features we don’t need from packages.
The business logic is decoupled from the access logic in our application; this makes it easier to maintain. If our ACL specs change, we probably won’t have to touch the controllers at all.
Next time I’ll make a post about using Gate with third party ACL packages.
via Laravel News http://ift.tt/2pS4XMF
0 notes
airman7com · 5 years ago
Text
PHP json encode – Convert Array To JSON, Object To JSON
The PHP json_encode () function function is used to convert PHP arrays or objects into JSON. PHP has some pre-built functions to handle JSON.
In this tutorial, we will learn how to convert PHP Object to JSON, convert PHP String to JSON, PHP Array To JSON, get data from JSON array in php convert Multidimensional PHP Array into JSON with definitions, syntax, and examples.
What is JSON?
JSON means…
View On WordPress
0 notes