Get Specific Columns Data Tutorial in Laravel 11
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// $post = Post::with("user")->get();
// if we want to fetch only specific columns data with "with()" method at that time
// we have to specify "foreign key" column name as shown below :
// $post = Post::with("user")->get(["title","description","user_id"]);
// if we want to fetch only specific columns data with "with()" method at that time
// we have to specify "primary key" column name as shown below :
// $post = Post::with("user:name,email,id")->get(["title","description","user_id"]);;
// we can use alias name of column name as shown below :
// $post = Post::with("user:name as User Name,email as User Email,id")->get(["title","description","user_id"]);
// $post = Post::with(["user" => function($query){
// $query->select("id","name","email");
// }])->get();
// $post = Post::with(["user" => function ($query) {
// $query->select("id", "name", "email");
// }])->get(["title", "description", "user_id"]);
// $post = Post::select("user_id", "title", "description")->with(["user" => function ($query) {
// $query->select("id", "name", "email");
// }])->get();
// $post = Post::select(["title","description","user_id"])->withWhereHas("user",function($query){
// $query->select("id","name","email")->where("city","Delhi");
// })->get();
// Till now we have fetched data from two tables only but if we want to fetch data from three
// tables (first table "users", second table "posts", third table "comments")then we can do as shown below :
// $post = Post::select(["title", "description", "user_id"])->with([
// "user" => function ($query) {
// $query->select("id", "name", "email");
// },
// "comments" => function ($query) {
// $query->select("post_id", "detail");
// }
// ])->get();
// Here below we have specified column names(of "users" table) in "Post" Model file
// we can check "Post" Model file
// $post = Post::with("user")->get();
// if we want to fetch all "users" table data along with "posts" table data everytime then we
// can specify in "Post" model file as shown in "Post" model file
// $post = Post::get();
// $post = Post::find(2);
// if we want to fetch only "posts" table data without "users" table data as shown below :
// $post = Post::without("user")->find(2);
// $post = Post::without("user")->get();
$post = Post::withOnly("user")->get();
return $post;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Above File is app\Http\Controllers\PostController File
Below File is app\Http\Controllers\UserController File
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// $user = User::get();
// $user = User::select("name","city")->get();
// $user = User::select("name","city")->where("city","Delhi")->get();
// $user = User::where("city","Delhi")->get(["name","email","city"]);
// $user = User::all("name","email")->toArray();
// $user = User::pluck("email");
// $user = User::pluck("email","name");
// $user = User::pluck("name","city"); //pluck() method will remove duplicates city names
// pluck() method will show only last value from duplicate records
// $user = User::where("city","Delhi")->pluck("name","city");
// $user = User::find(1);
// $user = User::find(1,["name","email"]);
// $user = User::findorfail(2,["name","email"]);
// $user = User::find(2)->email;
// $user = User::where("city","Delhi")->first()->email;
// $user = User::where("city","Delhi")->value("email");
// $user = User::where("city","Goa")->value("email");
// Here below we have specified column names(of "posts" table) in "User" Model file
// we can check "User" Model file
// $user = User::with("post")->get();
// Fetch "users" table data with "posts" table data in already existing query as shown below :
$user = User::all();
$user->load("post");
return $user;
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}
Below File is app\Models\Post File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $timestamps = true;
protected $table = "posts";
protected $fillable = ["title", "description", "status", "user_id"]; //First way, we can use anyone
// protected $guarded = []; //Second way, we can use anyone
protected $with = ["user"];
public function user()
{
return $this->belongsTo(User::class)->select(["name", "email", "id"]);
}
}
Below File is app\Models\User File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $timestamps = false;
protected $table = "users";
protected $fillable = ["name", "email", "city", "status"];
public function post()
{
return $this->hasMany(Post::class)->select(["title", "description", "user_id"]);
}
}
Below File is database\json\posts File
[
{
"title": "News Title One",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Two",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 2
},
{
"title": "News Title Three",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Four",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Five",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Six",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 1
},
{
"title": "News Title Seven",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 3
},
{
"title": "News Title Eight",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 2
},
{
"title": "News Title Nine",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"user_id": 4
}
]
Below File is database\json\users File
[
{
"name": "Yahoo Baba",
"email": "yahoobaba@gmail.com",
"city": "Delhi",
"status": 1
},
{
"name": "Salman Khan",
"email": "salman@gmail.com",
"city": "Mumbai",
"status": 0
},
{
"name": "Deepika Padukone",
"email": "deepika@gmail.com",
"city": "Delhi",
"status": 1
},
{
"name": "Abhishek Bachchan",
"email": "abhishek@gmail.com",
"city": "Goa",
"status": 1
}
]
Below File is database\migrations\2024_12_18_115130_create_users_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->string("email", 50)->unique();
$table->string("city");
$table->tinyInteger("status")->default(1);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Below File is database\migrations\2024_12_18_115842_create_posts_table File
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title", 50);
$table->longText("description");
$table->tinyInteger("status")->default(1);
$table->unsignedBigInteger("user_id");
$table->foreign("user_id")->references("id")->on("users")->onUpdate("cascade")->onDelete("cascade");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Below File is database\seeders\DatabaseSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
$this->call([
UserSeeder::class,
PostSeeder::class
]);
}
}
Below File is database\seeders\PostSeeder File
<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/posts.json");
$posts = collect(json_decode($json));
$posts->each(function ($post) {
Post::create([
"title" => $post->title,
"description" => $post->description,
"user_id" => $post->user_id
]);
});
}
}
Below File is database\seeders\UserSeeder File
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$json = File::get(path: "database/json/users.json");
$users = collect(json_decode($json));
$users->each(function ($user) {
User::create([
"name" => $user->name,
"email" => $user->email,
"city" => $user->city,
"status" => $user->status
]);
});
}
}
Below File is routes\web File
.png)
Comments
Post a Comment